使用举例
#!/usr/bin/python# coding:utf-8from apscheduler.schedulers.background import BackgroundSchedulerfrom datetime import datetimeimport timedef tick(): print('Tick! The time is: %s' % datetime.now())if __name__ == '__main__': scheduler = BackgroundScheduler() # 每隔5秒执行一次 scheduler.add_job(tick, 'interval', seconds=5) # 该部分调度是一个独立的线程 scheduler.start() try: # 模拟主进程持续运行 while True: time.sleep(2) print 'sleep' except(KeyboardInterrupt, SystemExit): # Not strictly necessary if daemonic mode is enabled but should be done if possible scheduler.shutdown() print('Exit The Job!')
说明:
BackgroundScheduler 运行在Backgroud,但是并不会阻止主程序自己终止,而主程序终止后,BackgroundScheduler 也会终止。
可以在代码后添加:
import timeprint("Waiting to exit") while True: time.sleep(1)
这样就能让scheduler 一直运行,而如果想终止,可以ctrl + C