【问题标题】:Run a function at the start of every round 5 minute interval在每轮开始时运行一个函数,间隔 5 分钟
【发布时间】:2020-02-26 06:51:34
【问题描述】:

我想每 5 分钟运行一次函数,它必须以“轮”间隔运行,例如:

12:05:00, 12:10:00, 12:15:00...

不可能是这样的:

12:06:00, 12:11:00, 12:16:00...

或者像这样:

12:05:14, 12:10:14, 12:15:14...

在 python 中最准确的方法是什么?

【问题讨论】:

  • 使用while 循环和if 每秒检查一次时间,这是其中一种时间,执行函数......但是:你提到计划任务的事实,让我认为你需要cron on linux 或 window 的任务调度器

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


【解决方案1】:

您可以使用threading.Timer。您必须做一些数学运算来计算下一次运行时间。 datetime 有一个方便的 replace 方法。

from datetime import datetime, timedelta
from threading import Timer

def get_sleep_time():
    now = datetime.now()
    next_run = now.replace(minute=int(now.minute / 5) * 5, second=0, microsecond=0) + timedelta(minutes=5)
    return (next_run - now).total_seconds()

def dowork():
    now = datetime.now()
    print('Doing some work at', now)
    schedule_next_run()

def schedule_next_run():
    sleep_time = get_sleep_time()
    print(f'sleeping for {sleep_time} seconds')
    t = Timer(sleep_time, dowork)
    t.daemon = True
    t.start()


print('Starting work schedule')
schedule_next_run()
input('Doing work every 5 minutes. Press enter to exit')

在我的系统上,函数在目标时间的半毫秒内触发

请注意,时间计算会四舍五入,然后添加timedelta 以仔细环绕每个小时的结束。您可能需要考虑这在夏令时更改时会如何表现。

建议:将所有这些逻辑移到一个类中进行清理。

【讨论】:

    【解决方案2】:
    import datetime, time
    
    def some_function():
    
    ran_once = True
    
    while True:
        current_time = datetime.datetime.now()
        if  current_time.minute % 5 == 0 and current_time.second % 60 == 0 and not ran_once:
            print(current_time) # DO YOUR WORK HERE
            ran_once = True
    
        elif current_time.minute % 5 == 0 or current_time.second % 60 != 0:
    
            if current_time.second % 60 == 0:
                print("Time to wait:", 5 - (current_time.minute % 5), "minutes and 0 seconds")
            else:
                print("Time to wait:", 4 - (current_time.minute % 5), "minutes and ", end="")
                print(60 - (current_time.second % 60), "seconds")
    
            time.sleep( (4 -(current_time.minute % 5))*60 + 60 -(current_time.second % 60))
    
            ran_once = False
    

    以上代码每隔 5 分钟运行一次。最初,主线程休眠达到完美时间戳所需的秒数。例如,如果程序在 7:28:30 开始,那么它将休眠 90 秒,然后在 7:30:00 开始。从那时起,它将等待 5 分钟,然后再次运行所需的功能。

    另外,我认为在确切的一秒启动的性能确实因系统处理线程的方式而异。

    【讨论】:

      【解决方案3】:

      您可以使用日期时间和条件。

      import datetime
      
      while True:
          current_time = datetime.datetime.now()
          if current_time.second % 5 == 0 and current_time.minute % 1 == 0 and current_time.microsecond == 0:
      
              print(current_time)
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-10
        • 2013-04-12
        • 2018-08-08
        • 1970-01-01
        • 2015-12-31
        • 2017-08-13
        • 1970-01-01
        • 2020-07-30
        相关资源
        最近更新 更多