Python 使用sched模块在给定时间运行

Python 使用sched模块在给定时间运行,python,scheduled-tasks,Python,Scheduled Tasks,我正在编写一个python脚本,它需要在两个给定时间之间运行。我需要使用内置的sched模块,因为这个脚本需要能够直接在任何拥有python 2.7 as的机器上运行,以减少配置时间。(因此CRON不是一个选项) 一些变量定义了运行时间的设置,此处set\u timer\u start=0600和set\u timer\u end=0900写入HHMM。我能够在正确的时间停止脚本 我不知道sched是如何工作的(python文档页面对我来说没有多大意义),但据我所知,它在某个日期/时间(历元)运

我正在编写一个python脚本,它需要在两个给定时间之间运行。我需要使用内置的
sched
模块,因为这个脚本需要能够直接在任何拥有python 2.7 as的机器上运行,以减少配置时间。(因此CRON不是一个选项)

一些变量定义了运行时间的设置,此处
set\u timer\u start=0600
set\u timer\u end=0900
写入
HHMM
。我能够在正确的时间停止脚本

我不知道
sched
是如何工作的(python文档页面对我来说没有多大意义),但据我所知,它在某个日期/时间(历元)运行,而我只希望它在给定的时间(
HHMM
)运行


有谁能给我一个关于如何使用调度程序的示例(或链接)并计算下一个运行日期/时间吗?

如果我没有弄错您的要求,您需要的可能是一个循环,它将在每次执行任务时在队列中重新输入任务。大致如下:

# 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

你刚刚成就了我的一天,我将使用第二个解决方案,因为这是最简单的,保留第一个作为备份(以防我的老板有其他计划)@s4uadmin-很高兴它对你有用。请记住,GUI是一个非常失败的基本实现,例如,如果输入诸如start=23、停止=01和不考虑分钟的东西。但是,通过使用函数
func(x)
替换范围内的
if x来改进它应该很简单,该函数将根据您的需要返回
True
False
。)
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.