1.简介
apscheduler是python中的任务定时模块,它包含四个组件:触发器(trigger),作业存储(job store),执行器(executor),调度器(scheduler).
2.安装
pip install apscheduler
3.示例
1 # coding=utf-8 2 from apscheduler.schedulers.blocking import BlockingScheduler 3 4 #作业1 5 def my_job1(): 6 print 'hello world!' 7 8 #作业2 9 def my_job2(name): 10 print 'hello world,', name 11 12 # 每个五秒运行一次函数 13 sched = BlockingScheduler() 14 #不带参数和和带有参数的函数 15 sched.add_job(my_job1, 'interval', seconds=5) 16 sched.add_job(func=my_job2, args=('tom',), trigger='interval', seconds=5) 17 sched.start()
4.讲解
关于触发器(trigger),它有三种参数可选:date / interval / cron.
date:一次性任务,即只执行一次任务。
参数如下:
next_run_time (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
示例如下:
# 延时五秒后执行一次 sched.add_job(func=my_job2, args=('tom',), trigger='date', next_run_time=now+datetime.timedelta(seconds=5))
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
示例如下:
#每隔五秒执行一次任务 sched.add_job(func=my_job2, args=('tom',), trigger='interval', seconds=5)
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)
示例如下:
#在1-3,8-10月,每天的下午5点,每一分钟执行一次任务 sched.add_job(func=my_job1, trigger='cron', month='1-3,8-10', day='*', hour='17', minute='*')