python cron定时任务
有个python小程序很占带宽,想把它放到下班时间运行。
在一番搜索后获取到APScheduler这一框架,并因其实现功能相对简单而无需过多配置,在此直接复制粘贴代码段以加快开发效率
# 我用的版本是3.5.1
from apscheduler.schedulers.blocking import BlockingScheduler
def start_job():
pass
def stop_job():
pass
def main():
sched = BlockingScheduler()
# 周一至周五下班开始任务
sched.add_job(start_job, 'cron', day_of_week='0-4', hour='19')
# 上班停止任务
sched.add_job(stop_job, 'cron', day_of_week='0-4', hour='9')
sched.start()
if __name__ == '__main__':
main()
最后,附上触发器支持参数
Parameters:
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)
jitter (int|None) – advance or delay the job execution by jitter seconds at most.
参考文档:http://apscheduler.readthedocs.io/en/latest/modules/triggers/cron.html]
