APScheduler

APScheduler

APScheduler简介

APScheduler(Advanced Python Scheduler)是一个轻量级的Python定时任务调度框架(Python库)。
APScheduler有三个内置的调度系统,其中包括:

  • cron式调度(可选开始/结束时间)
  • 基于间隔的执行(以偶数间隔运行作业,也可以选择开始/结束时间)
  • 一次性延迟执行任务(在指定的日期/时间内运行作业一次)

支持的后端存储作业

APScheduler可以任意混合和匹配调度系统和作业存储的后端,其中支持后端存储作业包括:

  • Memory
  • SQLAlchemy
  • MongoDB
  • Redis
  • RethinkDB
  • ZooKeeper

集成的Python框架

APScheduler内继承了几个常见的Python框架:

  • asyncio
  • gevent
  • tornado
  • qt

APScheduler下载安装

使用pip安装:

pip install apscheduler
pip install apscheduler==3.6.3

如果超时或者出现别的情况,可以选择:

# 方法1:使用豆瓣源下载
pip install -i https://pypi.doubanio.com/simple/ apscheduler
# 方法2:使用清华源下载
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple apscheduler

要是再不行,点击该链接或者pypi官网下载了。下载并解压缩,进入跟setup.py文件同级的目录,打开cmd,使用命令进行下载:

python setup.py install

APScheduler组件

回到顶部

APScheduler共有4种组件,分别是:

  • 触发器(trigger),触发器中包含调度逻辑,每个作业都有自己的触发器来决定下次运行时间。除了它们自己初始配置以外,触发器完全是无状态的。
  • 作业存储器(job store),存储被调度的作业,默认的作业存储器只是简单地把作业保存在内存中,其他的作业存储器则是将作业保存在数据库中,当作业被保存在一个持久化的作业存储器中的时候,该作业的数据会被序列化,并在加载时被反序列化,需要说明的是,作业存储器不能共享调度器。
  • 执行器(executor),处理作业的运行,通常通过在作业中提交指定的可调用对象到一个线程或者进程池来进行,当作业完成时,执行器会将通知调度器。
  • 调度器(scheduler),配置作业存储器和执行器可以在调度器中完成。例如添加、修改、移除作业,根据不同的应用场景,可以选择不同的调度器,可选的将在下一小节展示。

各组件简介

调度器

  • BlockingScheduler : 当调度器是你应用中唯一要运行的东西时。
  • BackgroundScheduler : 当你没有运行任何其他框架并希望调度器在你应用的后台执行时使用(充电桩即使用此种方式)。
  • AsyncIOScheduler : 当你的程序使用了asyncio(一个异步框架)的时候使用。
  • GeventScheduler : 当你的程序使用了gevent(高性能的Python并发框架)的时候使用。
  • TornadoScheduler : 当你的程序基于Tornado(一个web框架)的时候使用。
  • TwistedScheduler : 当你的程序使用了Twisted(一个异步框架)的时候使用
  • QtScheduler : 如果你的应用是一个Qt应用的时候可以使用。

作业存储器

如果你的应用在每次启动的时候都会重新创建作业,那么使用默认的作业存储器(MemoryJobStore)即可,但是如果你需要在调度器重启或者应用程序奔溃的情况下任然保留作业,你应该根据你的应用环境来选择具体的作业存储器。例如:使用Mongo或者SQLAlchemy JobStore (用于支持大多数RDBMS)

执行器

对执行器的选择取决于你使用上面哪些框架,大多数情况下,使用默认的ThreadPoolExecutor已经能够满足需求。如果你的应用涉及到CPU密集型操作,你可以考虑使用ProcessPoolExecutor来使用更多的CPU核心。你也可以同时使用两者,将ProcessPoolExecutor作为第二执行器。

触发器

当你调度作业的时候,你需要为这个作业选择一个触发器,用来描述这个作业何时被触发,APScheduler有三种内置的触发器类型:

  • date 一次性指定日期
  • interval 在某个时间范围内间隔多长时间执行一次
  • cron 和Linux crontab格式兼容,最为强大

指定定时任务执行的时机

1) date 在特定的时间日期执行

from datetime import date

# 在2019年11月6日00:00:00执行
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6))

# 在2019年11月6日16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5))
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05')

# 立即执行
sched.add_job(my_job, 'date')  
sched.start()

2) interval 经过指定的时间间隔执行

  • weeks (int) – number of weeks to wait

  • days (int) – number of days to wait

  • hours (int) – number of hours to wait

  • minutes (int) – number of minutes to wait

  • seconds (int) – number of seconds to wait

  • start_date (datetime|str) – starting point for the interval calculation

  • end_date (datetime|str) – latest possible date/time to trigger on

  • timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations

from datetime import datetime

# 每两小时执行一次
sched.add_job(job_function, 'interval', hours=2)

# 在2010年10月10日09:30:00 到2014年6月15日的时间内,每两小时执行一次
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')

3) cron 按指定的周期执行

  • year (int|str) – 4-digit year

  • month (int|str) – month (1-12)

  • day (int|str) – day of the (1-31)

  • week (int|str) – ISO week (1-53)

  • day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)

  • hour (int|str) – hour (0-23)

  • minute (int|str) – minute (0-59)

  • second (int|str) – second (0-59)

  • start_date (datetime|str) – earliest possible date/time to trigger on (inclusive)

  • end_date (datetime|str) – latest possible date/time to trigger on (inclusive)

  • timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone)

# 在6、7、8、11、12月的第三个周五的00:00, 01:00, 02:00和03:00 执行
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

# 在2014年5月30日前的周一到周五的5:30执行
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')

使用

当你需要调度作业的时候,你需要为这个作业选择一个触发器,用来描述该作业将在何时被触发,APScheduler有3中内置的触发器类型:

  • 新建一个调度器(scheduler)
  • 添加一个调度任务(job store)
  • 运行调度任务

添加作业

有两种方式可以添加一个新的作业:

  • add_job来添加作业
  • 装饰器模式添加作业

只执行一次

 date 触发器

import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
def job2(text):
    print('job2', datetime.datetime.now(), text)
scheduler = BlockingScheduler()
scheduler.add_job(job2, 'date', run_date=datetime.datetime(2019, 2, 25, 19, 5, 6), args=['text'], id='job2')
# 启动,加入任务存储器中 scheduler.start() #上例中,只在2010
-2-25 19:05:06执行一次,args传递一个text参数。

间隔执行

interval触发器

import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

def job1():
    print('job1', datetime.datetime.now())
scheduler = BlockingScheduler()
scheduler.add_job(job1, 'interval', seconds=5, id='job1')  # 每隔5秒执行一次
scheduler.add_job(job1, 'interval', hours=1, id='job1') # 每小时执行一次
# 启动,加入任务存储器中
scheduler.start()

 

周期执行

cron触发器

from apscheduler.schedulers.blocking import BlockingScheduler  # 后台运行
sc = BlockingScheduler()
f = open('t1.text', 'a', encoding='utf8')

# 每天凌晨1点30分50秒执行一次
# 使用装饰器方式
@sc.scheduled_job('cron', day_of_week='*', hour=1, minute='30', second='50')
def check_db():
    print(111111111111)
if __name__ == '__main__':
    try:
        sc.start()
        f.write('定时任务成功执行')
    except Exception as e:
        sc.shutdown()
        f.write('定时任务执行失败')
    finally:
        f.close()
import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

def job1():
    print('job1', datetime.datetime.now())
scheduler = BlockingScheduler()
# 每隔2分钟执行一次, */1:每隔1分钟执行一次
scheduler.add_job(job1, 'cron', minute="*/2", id='job1') 
scheduler.start()

 扩展

任务管理

方式1

job = scheduler.add_job(myfunc, 'interval', minutes=2)  # 添加任务
job.start() # 启动服务
job.remove()  # 删除任务
job.pause() # 暂定任务
job.resume()  # 恢复任务

方式2

scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')  # 添加任务    
scheduler.remove_job('my_job_id')  # 删除任务
scheduler.pause_job('my_job_id')  # 暂定任务
scheduler.resume_job('my_job_id')  # 恢复任务

调整任务调度周期

job.modify(max_instances=6, name='Alternate name')

scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')

停止APScheduler运行

scheduler.shutdown()

 

posted @ 2020-04-09 00:09  Mr沈  阅读(813)  评论(0编辑  收藏  举报