APScheduler模块四大组件:
触发器 triggers :用于设定触发任务的条件
任务储存器 job
stores:用于存放任务,把任务存放在内存或数据库中
执行器 executors: 用于执行任务,可以设定执行模式为单线程或线程池
调度器 schedulers: 把上方三个组件作为参数,通过创建调度器实例来运行
调度器组件详解
根据开发需求选择相应的组件,下面是不同的调度器组件:
BlockingScheduler
阻塞式调度器:适用于只跑调度器的程序。
BackgroundScheduler
后台调度器:适用于非阻塞的情况,调度器会在后台独立运行。
AsyncIOScheduler
AsyncIO调度器,适用于应用使用AsnycIO的情况。
GeventScheduler
Gevent调度器,适用于应用通过Gevent的情况。
TornadoScheduler
Tornado调度器,适用于构建Tornado应用。
TwistedScheduler
Twisted调度器,适用于构建Twisted应用。
QtScheduler
Qt调度器,适用于构建Qt应用。
配置一个任务,
设置一个任务触发器。触发器可以设定任务运行的周期、次数和时间。APScheduler有三种内置的触发器:
date 日期:触发任务运行的具体日期
interval 间隔:触发任务运行的时间间隔
cron 周期:触发任务运行的周期
from apscheduler.schedulers.blocking import BlockingScheduler import datetime,os,threading def func(): print('%s,%s,%s,%s'%((datetime.datetime.now()),'hello',os.getppid(),os.getpid())) if __name__ =='__main__': apsched = BlockingScheduler() apsched.add_job(func,'interval',seconds=5) #间隔调度interval apsched.start()
间隔调度对应值
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 apscheduler.schedulers.blocking import BlockingScheduler import datetime,os,threading def func(): print('%s,%s,%s,%s'%((datetime.datetime.now()),'hello',os.getppid(),os.getpid())) if __name__ =='__main__': apsched = BlockingScheduler() apsched.add_job(func,'cron',day_of_week='mon-fri',minute='*',second='*/3') #定时调度cron apsched.start()
定时调度
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)