python中的apscheduler模塊
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=‘*‘)
python中的apscheduler模塊