用python创建你的定时任务!

定时器库————APScheduler

引用文章

因为我也用地磕磕巴巴的,我就直接上文章了,真要用还得看大佬写的。

需要关注的地方

建议看完大佬们写的文章再看这些。

一个简单的定时任务程序可以这么写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from apscheduler.schedulers.bloking import BlockingScheduler
from datetime import datetime

def tick():
print(f'The time is {datetime.now()}')

if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
print('press Ctrl+C to exit')

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

其中:

BlockingScheduler是调度器。调度器的主循环其实就是反复检查是不是有到时需要执行的任务,调用start方法启动主循环。调度器的add_job方法就是往调度其中添加一个任务。apscheduler有不同的调度器,适用于不同的场景。

  • BlockingScheduler 适用于调度程序为进程中唯一运行的进程,调用它的start方法会阻塞当前线程,不能立即返回。
  • BackgroundScheduler 适用于调度程序在应用程序的后台运行,调用它的start方法后主线程不会阻塞。
  • AsyncIOScheduler 顾名思义,适用于使用了asyncio模块的应用程序。
  • GeventScheduler 适用于使用gevent模块的应用程序。
  • TwistedScheduler 适用于构建Twisted的应用程序。
  • QtScheduler 适用于构建Qt的应用程序。

add_job中的第二个参数'interval'是指定触发器类型。调度器scheduler会根据触发器trigger的规则来确定触发器绑定的任务job是否会被执行。

目前APScheduler支持三种触发器:

  1. DateTrigger 指定时间的触发器,对应传参为'date'

    1
    2
    # The job will be executed on November 6th, 2009
    sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])
  2. IntervalTrigger 指定间隔时间的触发器,对应传参为'interval'

    1
    2
    3
    4
    5
    #表示每隔3天17时19分07秒执行一次任务
    sched.add_job(my_job,
    'interval',
    days = 3,hours =17,minutes =19,seconds=7
    )
  3. CronTrigger 类似Linux系统中的Crontab,对应传参为'cron'

    1
    2
    3
    4
    5
    6
    7
    8
    #表示任务在6,7,8,11,12月份的第三个星期五的00:00,01:00,02:00,03:00 执行该程序
    sched.add_job(my_job, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

    #表示从星期一到星期五5:30(AM)直到2014-05-30 00:00:00
    sched.add_job(my_job, 'cron', day_of_week='mon-fri', hour=5, minute=30,end_date='2014-05-30')

    #表示每5秒执行该程序一次,相当于interval 间隔调度中seconds = 5
    sched.add_job(my_job, 'cron',second = '*/5')

    cron参数时间表达式规则:

    表达式 作用域 描述
    * any Fire on every value.(Fire on直译为开火的意思,联系上下文及正则表达式相关知识,这里的Fire on应该是有“指向”的意味。)匹配所有字符。表示匹配该域的任意值,假如在Minutes域使用*, 即表示每分钟都会触发事件。
    */a any Fire every a values, starting from the minimum. 匹配每一个“a”值,从最小值(第一个?)开始。 / 表示起始时间开始触发,然后每隔固定时间触发一次,例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次.
    a-b any Fire on any value within the a-b range(a must be smaller than b). 匹配每一个在[a,b]中的数,a必须小于b。
    a-b/c any Fire every c values within the a-b range. 匹配[a,b]中所有c值。
    xth y day Fire on the x-th occurrence of weekday y within the month.匹配一个月份里第y个工作日(即周一、周二等)的第x次出现的时间。
    last x day Fire on the last occurrence of weekday x within the month.匹配一个月份里第x个工作日(即周一、周二等)最后一次出现的时间。
    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. 匹配表达式,可由上述表达式组合而成。这里的的重点是逗号的使用

    可以参考一下Linux中Crontab中cron表达式是怎么写的,会很有启发。

    cron表达式详解 - heart - 博客园 (cnblogs.com)