Search code examples
pythontimedelayclockmodulo

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


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)

Solution

  • 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.