Search code examples
pythontimer

How to repeatedly execute a function every x seconds?


I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C or setTimeout in JS). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.

In this question about a cron implemented in Python, the solution appears to effectively just sleep() for x seconds. I don't need such advanced functionality so perhaps something like this would work

while True:
    # Code executed here
    time.sleep(60)

Are there any foreseeable problems with this code?


Solution

  • If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

    import sched, time
    
    def do_something(scheduler): 
        # schedule the next call first
        scheduler.enter(60, 1, do_something, (scheduler,))
        print("Doing stuff...")
        # then do your stuff
    
    my_scheduler = sched.scheduler(time.time, time.sleep)
    my_scheduler.enter(60, 1, do_something, (my_scheduler,))
    my_scheduler.run()
    

    If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.