使用 sched 模块在给定时间运行 [英] Use sched module to run at a given time

查看:59
本文介绍了使用 sched 模块在给定时间运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a python script that needs to run between two given times. I'm required to use the build in sched module as this script needs to be able to run directly on any machine that has python 2.7 as to reduce configuration time. (SO CRON IS NOT AN OPTION)

一些变量定义了运行时间的设置,这里set_timer_start=0600set_timer_end=0900 是用HHMM 编写的.我能够在正确的时间停止脚本.

A few variables define the settings for the time to run, here set_timer_start=0600 and set_timer_end=0900 are written in HHMM. I'm able to stop the script at the right time.

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

I don't know exactly how sched works (the python doc page doesn't make to much sense to me), but as far as I understand It runs at a date/time (epoch) while I only want it to run at a given time (HHMM).

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

Can anyone give me an example (or link) on how to use the scheduler and perhaps calculate the next run date/time?

推荐答案

如果我理解你的要求,你需要的可能是一个循环,它会在每次执行时重新进入队列中的任务.类似的东西:

If I got your requirements right, what you need is probably a loop, that will re-enter a task in the queue every time it will be executed. Something along the lines of:

# 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

然而,使用调度程序是 - IMO - 矫枉过正.使用 datetime 对象就足够了,例如一个基本的实现看起来像:

However, using the scheduler is - IMO - overkilling. Using datetime objects could suffice, for example a basic implementation would look like:

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.

HTH!

这篇关于使用 sched 模块在给定时间运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆