pip install apscheduler
触发器中包含调度逻辑,每一个做业都由本身的触发器来决定下次运行时间。除了他们本身初始配置意外,触发器彻底是无状态的。html
# 每两个小时调一下job_function sched.add_job(job_function, 'interval', hours=2)
(int|str) 表示参数既能够是int类型,也能够是str类型
(datetime | str) 表示参数既能够是datetime类型,也能够是str类型python
参数的取值格式:react
Expressiongit |
Fieldweb |
Descriptionredis |
*sql |
anymongodb |
Fire on every value数据库 |
*/aexpress |
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 |
#表示2017年3月22日17时19分07秒执行该程序 sched.add_job(my_job, 'cron', year=2017,month = 03,day = 22,hour = 17,minute = 19,second = 07) #表示任务在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')
run_date (datetime|
str
) – the date
/
time to run the job at
-
(任务开始的时间)
timezone (datetime.tzinfo|
str
) – time zone
for
run_date
if
it doesn’t have one already
#在指定的时间,只执行一次 scheduler.add_job(tick, 'date', run_date='2016-02-14 15:01:05') # The job will be executed on November 6th, 2009 sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text']) # 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'])
存储被调度的做业,默认的做业存储器只是简单地把做业保存在内存中,其余的做业存储器则是将做业保存在数据库中。看成业被保存到一个持久化的做业存储器中的时候,该做业的数据会被序列化,并在加载时被反序列化。做业存储器不能共享调度器。
jobstore提供给scheduler一个序列化jobs的统一抽象,提供对scheduler中job的增删改查接口,根据存储backend的不一样,分如下几种:
处理做业的运行,他们一般经过在做业中提交指定的可调用对象到一个线程或者进城池来进行。看成业完成时,执行器将会通知调度器。
配置做业存储器和执行器能够在调度器中完成,例如添加、修改和移除做业。根据不一样的应用场景能够选用不一样的调度器。
可选的有BlockingScheduler、BackgroundScheduler、AsyncIOScheduler、GeventScheduler、TornadoScheduler、TwistedScheduler、QtScheduler 7种。
简单实例
import time from apscheduler.schedulers.blocking import BlockingScheduler def test_job(): print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) scheduler = BlockingScheduler() #该示例代码生成了一个BlockingScheduler调度器,使用了默认的默认的任务存储MemoryJobStore,以及默认的执行器ThreadPoolExecutor,而且最大线程数为10。 scheduler.add_job(test_job, 'interval', seconds=5, id='test_job') #该示例中的定时任务采用固定时间间隔(interval)的方式,每隔5秒钟执行一次。 #而且还为该任务设置了一个任务id scheduler.start()
若是想执行一些复杂任务,如上边所说的同时使用两种执行器,或者使用多种任务存储方式,而且须要根据具体状况对任务的一些默认参数进行调整。能够参考下面的方式。
(http://apscheduler.readthedocs.io/en/latest/userguide.html)
from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler # 导入调度器 from apscheduler.jobstores.mongodb import MongoDBJobStore # 导入做业存储 from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore # 导入做业存储 from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor # 导入执行器 jobstores = { 'mongo': MongoDBJobStore(), 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 3 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
from apscheduler.schedulers.background import BackgroundScheduler # The "apscheduler." prefix is hard coded scheduler = BackgroundScheduler({ 'apscheduler.jobstores.mongo': { 'type': 'mongodb' }, 'apscheduler.jobstores.default': { 'type': 'sqlalchemy', 'url': 'sqlite:///jobs.sqlite' }, 'apscheduler.executors.default': { 'class': 'apscheduler.executors.pool:ThreadPoolExecutor', 'max_workers': '20' }, 'apscheduler.executors.processpool': { 'type': 'processpool', 'max_workers': '5' }, 'apscheduler.job_defaults.coalesce': 'false', 'apscheduler.job_defaults.max_instances': '3', 'apscheduler.timezone': 'UTC', })
from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ProcessPoolExecutor jobstores = { 'mongo': {'type': 'mongodb'}, 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') } executors = { 'default': {'type': 'threadpool', 'max_workers': 20}, 'processpool': ProcessPoolExecutor(max_workers=5) } job_defaults = { 'coalesce': False, 'max_instances': 3 } scheduler = BackgroundScheduler() # .. do something else here, maybe add jobs etc. scheduler.configure(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)