详解高级Python调度器APScheduler

APScheduler介绍

1. 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.

2. APScheduler有四种组件:

  • Triggers (触发器)

触发器包含调度逻辑,每个作业都有自己的触发器,根据设置的trigger规则,决定下一步应该在什么时候运行作业,除了初始配置之外,触发器是完全无状态的。

  • Job stores (作业存储器)

用于存放任务,Jobstore在scheduler中初始化,通过scheduler的add_jobstore动态添加Jobstore,把任务存放在内存(为默认MemoryJobStore)或数据库中。当作业被存放在数据库中时,它会被序列化,当被重新加载时会反序列化。作业存储器充当保存、加载、更新和查找作业的中间件。同时在调度器之间不能共享作业存储。

  • Executors (执行器)

执行器是将任务提交到线程池或进程池中运行,当任务完成时,执行器通知调度器触发相应的事件。每个executor都会绑定一个alias,这个作为唯一标识绑定到Job,在实际执行时会根据Job绑定的executor找到实际的执行器对象,然后根据执行器对象执行Job。

  • Schedulers (调度器)

把触发器、作业存储器、执行器三个组件作为参数,通过创建调度器实例来运行。通过Schedulers 配置作业存储器、执行器和触发器,添加、修改和删除任务。通常只有一个调度程序运行在应用程序中,开发人员通常不需要直接处理作业存储器、执行器或触发器,只需要通过调度器来完成的。

BlockingScheduler 阻塞式调度器:适用于只跑调度器的程序。

BackgroundScheduler 后台调度器:适用于非阻塞的情况,调度器会在后台独立运行。

AsyncIOScheduler AsyncIO调度器,适用于应用使用AsnycIO的情况。

GeventScheduler Gevent调度器,适用于应用通过Gevent的情况。

TornadoScheduler Tornado调度器,适用于构建Tornado应用。

TwistedScheduler Twisted调度器,适用于构建Twisted应用。

QtScheduler Qt调度器,适用于构建Qt应用。

四种组件具体使用方法

1. Triggers 触发器

  • apscheduler.triggers.date

这是调度job最简单的方法,一个作业在指定的时间执行一次。

image.png

from datetime import date
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
def my_job(text):
    print(text)

# The job will be executed on November 6th, 2009
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])

sched.start()

指定job应该运行的确切时间:

# The job will be executed on November 6th, 2009 at 16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])

运行日期也可以以文本形式给出:

sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05', args=['text'])
添加要立即运行的job:
# The 'date' trigger and datetime.now() as run_date are implicit
sched.add_job(my_job, args=['text'])
  • apscheduler.triggers.cron

这是APScheduler中最强大的内置触发器,每个字段可以指定不同的表达式,通过找到满足每个字段条件来确定下一次的执行时间。

image.png

例如,在每年的每个月的第一天,每小时的第20分钟执行,参数可以这样定义: 

year='*', month='*', day=1, week='*', day_of_week='*', hour='*', minute=20, second=0

 

下面表中列出了从year到second字段中使用的所有可用表达式,多个表达式可以在单个字段中给出,用逗号分隔:

image.png

Examples:

from apscheduler.schedulers.blocking import BlockingScheduler
def job_function():
    print "Hello World"

sched = BlockingScheduler()

# Schedules job_function to be run on the third Friday
# of June, July, August, November and December at 00:00, 01:00, 02:00 and 03:00
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

sched.start()

可以使用start_date和end_date来限制时间表运行的总时间:

# Runs from Monday to Friday at 5:30 (am) until 2014-05-30 00:00:00
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')

同时也可以使用 scheduled_job() 装饰器:

@sched.scheduled_job('cron', id='my_job_id', day='last sun')
def some_decorated_task():
    print("I am printed at 00:00:00 on the last Sunday of every month!")

使用标准crontab表达式调度job:

sched.add_job(job_function, CronTrigger.from_crontab('0 0 1-15 may-aug *'))

如果有多个服务,不希望同一时间调用同一个job,可以通过定义随机时间来调用job:

# Run the `job_function` every sharp hour with an extra-delay picked randomly in a [-120,+120] seconds window.
sched.add_job(job_function, 'cron', hour='*', jitter=120)
  • apscheduler.triggers.interval

此方法按选定的间隔定期调度job运行,同时可以通过start_date和end_date参数来指定计划的开始日期和结束日期。

image.png

Examples:

from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
def job_function():
    print("Hello World")

sched = BlockingScheduler()

# Schedule job_function to be called every two hours
sched.add_job(job_function, 'interval', hours=2)

sched.start()

可以使用start_date和end_date来限制时间表运行的总时间:

@sched.scheduled_job('interval', id='my_job_id', hours=2)
def job_function():
    print("Hello World")

同时也可以使用 scheduled_job() 装饰器:

@sched.scheduled_job('interval', id='my_job_id', hours=2)
def job_function():
    print("Hello World")

如果有多个服务,不希望同一时间调用同一个job,可以通过定义随机时间来调用job,如每隔一个小时调用1次job,但在[-120,+120]秒窗口中随机选择额外的延迟时间:

# Run the `job_function` every hour with an extra-delay picked randomly in a [-120,+120] seconds window.
sched.add_job(job_function, 'interval', hours=1, jitter=120)

以上先描述Triggers 触发器的使用,后面会继续讲解其他组件的搭配使用。

END

----------------------------------------------------------------

欢迎关注我的公众号,每天八点半更多干活准时送达!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值