Python中APScheduler模块的使用

本文介绍了APScheduler,一个用于Python的灵活且强大的任务调度库。通过示例代码展示了如何使用add_job方法及scheduled_job装饰器来执行一次性或周期性的任务。文中还详细解释了cron表达式的各个字段含义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"


 


 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值