What is the best way to run a function every 5 minutes in python synced with system clock?

一笑奈何 提交于 2020-01-14 04:32:06

问题


I want to run a function every 5 minutes and have it synced with the clock. If I use time.sleep(60*5), the time starts to drift because my function adds a tiny bit of processing time. Is this a good way of running my function synced with the clock or is there a better way in python?

def run(condition):

    def task():
        #run data here
        pass

    runOnce = True

    while condition:
        if dt.datetime.now().minute % 5 == 0 and dt.datetime.now().second == 0 and runOnce:
            runOnce = False
            task()

        elif dt.datetime.now().second != 0 and not runOnce:
            runOnce = True

        else:
            time.sleep(0.5)




run(True)

回答1:


You can try APScheduler. It uses python's datetime module to control the execution thus should be largely independent of your code's peculiarities.

from apscheduler.scheduler import BlockingScheduler

@sched.scheduled_job('interval', id='my_job_id', minutes=5)
def job_function():
    print("Hello World")

Python also has an inbuilt scheduler, python's sched module with a bit simpler api that should perform in the same way and save you some hassle from maintaining an extra dependency.



来源:https://stackoverflow.com/questions/59061828/what-is-the-best-way-to-run-a-function-every-5-minutes-in-python-synced-with-sys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!