如何让python代码在y和z之间循环每x分钟?

时间:2022-03-11 14:30:19

This might be incredibly easy but how do I get python code to loop every x mins between the times y and z?

这可能非常简单但是如何让python代码在y和z之间循环每x分钟?

For example if I wanted my script to run between midnight (00:00) through to 10 pm (22:00) looping every 5 minutes.

例如,如果我希望我的脚本在午夜(00:00)到晚上10点(22:00)之间运行,每5分钟循环一次。

1 个解决方案

#1


8  

Try the sched module in the standard library. Here's an example of calling a function once per second, starting five seconds in the future, and ending ten seconds in the future:

尝试标准库中的sched模块。这是一个每秒调用一次函数的例子,将来五秒开始,将来十秒结束:

from sched import scheduler
from time import time, sleep

s = scheduler(time, sleep)

def run_periodically(start, end, interval, func):
    event_time = start
    while event_time < end:
        s.enterabs(event_time, 0, func, ())
        event_time += interval
    s.run()

if __name__ == '__main__':

    def say_hello():
        print 'hello'    

    run_periodically(time()+5, time()+10, 1, say_hello)

Alternatively, you can work with threading.Timer, but you need to do a little more work to get it to start at a given time, run every five minutes, and stop at a fixed time.

或者,您可以使用threading.Timer,但是您需要做一些工作才能让它在给定时间启动,每五分钟运行一次,并在固定时间停止。

#1


8  

Try the sched module in the standard library. Here's an example of calling a function once per second, starting five seconds in the future, and ending ten seconds in the future:

尝试标准库中的sched模块。这是一个每秒调用一次函数的例子,将来五秒开始,将来十秒结束:

from sched import scheduler
from time import time, sleep

s = scheduler(time, sleep)

def run_periodically(start, end, interval, func):
    event_time = start
    while event_time < end:
        s.enterabs(event_time, 0, func, ())
        event_time += interval
    s.run()

if __name__ == '__main__':

    def say_hello():
        print 'hello'    

    run_periodically(time()+5, time()+10, 1, say_hello)

Alternatively, you can work with threading.Timer, but you need to do a little more work to get it to start at a given time, run every five minutes, and stop at a fixed time.

或者,您可以使用threading.Timer,但是您需要做一些工作才能让它在给定时间启动,每五分钟运行一次,并在固定时间停止。