使用APScheduler3.0.1 实现定时任务的方法
技术  /  管理员 发布于 7年前   300
需求是在某一指定的时刻执行操作
网上的建议多为通过调用Scheduler的add_date_job实现
不过APScheduler 3.0.1与之前差异较大, 无法通过上述方法实现
参考 https://apscheduler.readthedocs.org/en/latest/userguide.html APScheduler 3.0.1的userguide 解决问题
from datetime import datetimeimport timeimport os from apscheduler.schedulers.background import BackgroundScheduler def tick(): print('Tick! The time is: %s' % datetime.now()) if __name__ == '__main__': scheduler = BackgroundScheduler() scheduler.add_job(tick, 'interval', seconds=3) scheduler.start() print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C')) try: # This is here to simulate application activity (which keeps the main thread alive). while True: time.sleep(2) except (KeyboardInterrupt, SystemExit): scheduler.shutdown() # Not strictly necessary if daemonic mode is enabled but should be done if possible
实例的代码实现每3秒执行一次tick方法,虽然与需求不符,但发现add_interval_job在APScheduler 3.0.1中 已经被
scheduler.add_job(tick, 'interval', seconds=3)
取代。
help(scheduler.add_job)得到
add_job(func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', replace_existing=False, **trigger_args)Adds the given job to the job list and wakes up the scheduler if it's already running. Any option that defaults to undefined will be replaced with the corresponding default value when the job is scheduled (which happens when the scheduler is started, or immediately if the scheduler is already running). The func argument can be given either as a callable object or a textual reference in the package.module:some.object format, where the first half (separated by :) is an importable module and the second half is a reference to the callable object, relative to the module. The trigger argument can either be:the alias name of the trigger (e.g. date, interval or cron), in which case any extra keyword arguments to this method are passed on to the trigger's constructoran instance of a trigger class
由此可知,第参数为trigger,可取值为 date、interval、cron, **trigger_args为该trigger的构造函数。
通过源码找到DateTrigger 的构造函数
def __init__(self, run_date=None, timezone=None)
所以,只需将指定的时间传入add_job
scheduler.add_job(tick, 'date', run_date='2014-11-11 14:48:00')
以上这篇使用APScheduler3.0.1 实现定时任务的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号