Pthon的定时任务APScheduler的启动与关闭

Pthon的定时任务APScheduler的启动与关闭

安装:

sudo pip install apscheduler

使用:
直接运行Python文件即可,如 python XXX.py,XXX.py为你的Python文件

使用实例

	 #coding=utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
import time
import os

class spider(object):
	def tick(self):
		print('Test APScheduler - time is: %s' % datetime.now())

def runapp():
	mySpider = spider()
	mySpider.tick()


if __name__ == '__main__':
	 
	scheduler = BlockingScheduler()
	scheduler.add_job(runapp,'cron', second='*/3', hour='*') 
	print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
	try:
		scheduler.start()
	except (KeyboardInterrupt, SystemExit):
		scheduler.shutdown() 

详细的具体使用可参照后文的链接

注意,我们在终端中执行的话,直接关闭终端窗口,Python任务是会中断的。以下是解决方案

在您关闭终端,Python进程会被杀死,程序将停止运行。所以建议使用以下的方法运行,

python scrip.py &

这样即使关闭了终端窗口,程序也不受到影响,当我们想强制停止程序的时候,可以使用以下的指令:

ps -e | grep python

终端中输出:

88264 ??         0:00.21 /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u /Users/***/APScheduler_back.py
89726 ttys001    0:00.00 grep python

再使用以下结束Python的进程:

kill 88264

参考:

Python任务调度模块 – APScheduler

Stop Advanced Python Scheduler Job After Closing Terminal

原文地址:https://www.cnblogs.com/fengtengfei/p/5664932.html