HTD*_*chy 7 python scheduled-tasks
我正在研究一个需要在两个给定时间之间运行的python脚本.我需要使用build in sched模块,因为这个脚本需要能够在任何具有python 2.7的机器上直接运行,以减少配置时间.(所以CRON不是一个选项)
一些变量定义了运行时间的设置,这里set_timer_start=0600和set_timer_end=0900写入HHMM.我能够在合适的时间停止脚本.
我不知道究竟是如何sched工作的(python doc页面对我来说没有多大意义),但据我所知,它运行在日期/时间(epoch),而我只希望它在给定的运行时间(HHMM).
任何人都可以给我一个关于如何使用调度程序的示例(或链接),也许可以计算下一个运行日期/时间?
mac*_*mac 11
如果我的要求是正确的,那么你需要的可能就是一个循环,它会在每次执行时重新进入队列中的任务.有点像:
# 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
Run Code Online (Sandbox Code Playgroud)
但是,使用调度程序是 - IMO - 过度使用.使用datetime对象就足够了,例如基本实现看起来像:
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.
Run Code Online (Sandbox Code Playgroud)
HTH!