python中定时任务使用
文章目录
一、简介
python中定时任务使用apscheduler(advanced python scheduler)。
二、知识点
2.1 文档官网地址
文档官网地址为:https://apscheduler.readthedocs.io/en/latest/userguide.html
2.2 安装
pip install apscheduler
2.3 组合
apscheduler由作业(job)、作业存储(jobstore)、调度器(scheduler)、执行器(executor)、触发器(trigger)、监听器(listener)组成。
2.3.1 作业
作业(job)其实就是自定义的函数。
2.3.2 作业存储
作业存储(jobstore)指作业存储的位置,可以在内存中,也可以持久化到其它存储中,常用如:
MemoryJobStore:默认
MongoDBJobStore
RedisJobStore
RethinkDBJobStore
SQLAlchemyJobStore
ZooKeeperJobStore
2.3.4 调度器
调度器(scheduler)用于作业的添加、修改、删除等操作,常用调度器有:
BlockingScheduler: 当前程序中使用,调用start方法后会阻塞主线程
BackgroundScheduler: 程序后台使用,调用start方法后不会阻塞主线程
AsyncIOScheduler: use if your application uses the asyncio module
GeventScheduler: use if your application uses gevent
TornadoScheduler: use if you’re building a Tornado application
TwistedScheduler: use if you’re building a Twisted application
QtScheduler: use if you’re building a Qt application
2.2.5 执行器
执行器(executor)用于作业的真正执行,通常是在线程池中完成。
ThreadPoolExecutor:默认
ProcessPoolExecutor:适用于cpu密集型
AsyncIOExecutor
GeventExecutor
TornadoExecutor
TwistedExecutor
2.3.6 触发器
触发器(trigger)触发作业的执行,即指定作业什么时候执行,常用有:
date:在指定时间执行
interval: 指定间隔时间执行
cron: 根据cron规则执行
2.3.6 监听器
监听器(listener)用于监听事件,也是一个函数,用于在特定事件执行自定义操作。监听事件有:
'EVENT_SCHEDULER_STARTED', 'EVENT_SCHEDULER_SHUTDOWN', 'EVENT_SCHEDULER_PAUSED',
'EVENT_SCHEDULER_RESUMED', 'EVENT_EXECUTOR_ADDED', 'EVENT_EXECUTOR_REMOVED',
'EVENT_JOBSTORE_ADDED', 'EVENT_JOBSTORE_REMOVED', 'EVENT_ALL_JOBS_REMOVED',
'EVENT_JOB_ADDED', 'EVENT_JOB_REMOVED', 'EVENT_JOB_MODIFIED', 'EVENT_JOB_EXECUTED',
'EVENT_JOB_ERROR', 'EVENT_JOB_MISSED', 'EVENT_JOB_SUBMITTED', 'EVENT_JOB_MAX_INSTANCES',
'SchedulerEvent', 'JobEvent', 'JobExecutionEvent', 'JobSubmissionEvent'
2.4 核心函数
BaseScheduler下的add_job为添加作业方法,定义如下:
def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None,