python scheduler_python中的apscheduler模块

1.简介

apscheduler是python中的任务定时模块,它包含四个组件:触发器(trigger),作业存储(job store),执行器(executor),调度器(scheduler).

2.安装

pip install apscheduler

3.示例

1 #coding=utf-8

2 from apscheduler.schedulers.blocking importBlockingScheduler3

4 #作业1

5 defmy_job1():6 print 'hello world!'

7

8 #作业2

9 defmy_job2(name):10 print 'hello world,', name11

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='*')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值