使用sched模块在指定时间运行
我正在写一个Python脚本,这个脚本需要在两个指定的时间之间运行。我必须使用内置的sched
模块,因为这个脚本需要能够直接在任何安装了Python 2.7的机器上运行,以减少配置时间。(所以不能用CRON)
有几个变量定义了运行的时间设置,这里set_timer_start=0600
和set_timer_end=0900
是以HHMM
的格式写的。我能在正确的时间停止脚本。
我不太明白sched
是怎么工作的(Python的文档对我来说有点难懂),但我理解的是它是在某个具体的日期/时间(纪元时间)运行,而我只想让它在指定的时间(HHMM
)运行。
有没有人能给我一个例子(或者链接),教我怎么使用这个调度器,或者怎么计算下次运行的日期/时间?
1 个回答
12
如果我理解你的需求没错的话,你可能需要一个循环,每次执行任务时都会把这个任务重新放回队列里。大概是这样的:
# This code assumes you have created a function called "func"
# that returns the time at which the next execution should happen.
s = sched.scheduler(time.time, time.sleep)
while True:
if not s.queue(): # Return True if there are no events scheduled
time_next_run = func()
s.enterabs(time_next_run, 1, <task_to_schedule_here>, <args_for_the_task>)
else:
time.sleep(1800) # Minimum interval between task executions
不过,我觉得使用调度器有点过于复杂了。其实用日期时间对象就可以满足需求,比如一个简单的实现可以是:
from datetime import datetime as dt
while True:
if dt.now().hour in range(start, stop): #start, stop are integers (eg: 6, 9)
# call to your scheduled task goes here
time.sleep(60) # Minimum interval between task executions
else:
time.sleep(10) # The else clause is not necessary but would prevent the program to keep the CPU busy.
希望这对你有帮助!