您的位置:首页 > 编程语言 > Python开发

Python中APScheduler模块的使用

2016-01-26 16:41 513 查看

APScheduler介绍

Advanced Python Scheduler (APScheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. You can add new jobs or remove old ones on the fly as you please. If you store your jobs in a database,
they will also survive scheduler restarts and maintain their state. When the scheduler is restarted, it will then run all the jobs it should have run while it was offline.

个人翻译:

APScheduler是一个Python库,它能够让你安排你的Python代码延后执行、执行一次或者定期执行。你可以随意添加新的任务或删除旧的任务。如果用数据库存储任务,调度程序重启期间会维护任务的状态。当调度程序重启后,将运行所有本应在掉线时执行的任务。

代码

可以采用两种方式添加任务,调用add_job()方法或使用scheduled_job()装饰器。

调用add_job方法:

import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

def test():
print "now is '%s' " % datetime.datetime.now()

scheduler.add_job(test, "cron", second="*/3")

try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()

使用装饰器:

import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

@scheduler.scheduled_job("cron", second="*/3")
def test():
print "now is '%s' " % datetime.datetime.now()

try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown(

cron表达式说明 

Expression
Field
Description
*
any
Fire on every value
*/a
any
Fire every a values, starting from the minimum
a-b
any
Fire on any value within the a-b range (a must be smaller than b)
a-b/c
any
Fire every c values within the a-b range
xth y
day
Fire on the x -th occurrence of weekday y within the month
last x
day
Fire on the last occurrence of weekday x within the month
last
day
Fire on the last day within the month
x,y,z
any
Fire on any matching expression; can combine any number of any of the above expressions

参考资料

# 官方文档
apschedule_docs = "http://apscheduler.readthedocs.org/en/latest/index.html"

# Python定时任务框架APScheduler 3.0.3 Cron示例
blog1 = "http://www.cnblogs.com/leleroyn/p/4501359.html"


 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: