【问题标题】:How to Run Python Code 30 Sec before Every 5th Minute如何在每 5 分钟之前运行 Python 代码 30 秒
【发布时间】:2019-03-03 12:33:59
【问题描述】:

我有一个 python 程序,我想在每 5 分钟前准确执行 30 秒,并且只需要运行 30 秒。

【问题讨论】:

标签: python python-3.x scheduled-tasks


【解决方案1】:

与其一遍又一遍地循环和测试是否是正确的时间,不如计算等待所需的时间,并在此之前休眠,以便处理器可以关闭并执行其他操作。为此,我们仍然使用datetime 模块和一些简单的数学运算。

from datetime import datetime as dt
from time import sleep

#Calculating sleep interval
t = dt.now()
#seconds in the hour
sec = t.second + t.minute*60
#seconds since the last 5 min interval
sec = sec % 300
#until the next 5 min interval
sec = 300 - sec
#30 sec before that
sec = sec - 30
#if negative we're within 30 sec of 5 minute interval so goto next one
if sec < 0:
    sec = sec + 300
sleep(sec)

while True: #loop forever
    #with a little re-arranging and boolean math, this can all be condensed to:
    t = dt.now()
    s = (t.second + 60*t.minute) % 300
    sleep(270 - s + 300 * (s >= 270))
    #yourFunction()

对于非常简单的情况,这应该有效。如果您的程序在任何时候崩溃,或者计算机重新启动或无数其他原因,最好使用操作系统内置的东西,它会自动重新启动程序,并且可以处理其他情况,例如设置睡眠定时器,或仅在特定用户登录时执行。在 Windows 上这是任务调度程序,在 Linux 上这通常是 cron,并且 OSX 已启动(至少根据 developer.apple.com)

【讨论】:

    【解决方案2】:

    如果您不明确地运行此代码,我建议您关注 Aaron 的建议,看看 superuser.comapple.stackexchange.comaskubuntu.com

    但是,如果您打算用 Python 编写此代码,则可以使用 datetime 模块并查找经过的时间。

    from datetime import datetime
    import time
    
    
    def your_function(t1):
        i = 0
        # For the next 30 seconds, run your function
        while (datetime.now() - t1).seconds =< 30:
            i += 1
            print(i)
            time.sleep(1)
    
    
    # Run indefintely
    while True:
    
        # Record the current time
        t1 = datetime.now()
        while t1:
    
            # Find the elapsed time in seconds 
            # If the difference is 270 seconds (4 minutes and 30 seconds)
            if (datetime.now()-t1).seconds == 270:
                    your_function(t1)
    
                # Remove t1 and start at the top of the loop again
                t1 = None
    

    【讨论】:

    • 如果我在 python 中实现 cron,我会改变一些事情:你不能特别依赖你的 if 语句发生在精确的第二个,所以你应该使用一个相对运算符:@987654327 @。计时远不能保证,因此您应该与时钟时间进行比较,而不是仅以 5 分钟的间隔进行比较,以防止漂移。真的,我只需计算一次到下一个间隔的增量,然后再计算一次time.sleep。无论您做什么,您都将受到操作系统调度线程的支配,因此您最好在此之前休眠以节省 CPU 周期。
    猜你喜欢
    • 1970-01-01
    • 2020-03-06
    • 2022-12-18
    • 2016-02-14
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多