What is the best way to repeatedly execute a function every x seconds in Python?


I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). 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

Are there any foreseeable problems with this code?

5/23/2017 12:18:26 PM

Accepted Answer

Use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print "Doing stuff..."
    # do your stuff
    s.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
8/31/2016 3:31:13 PM

Just lock your time loop to the system clock. Easy.

import time
while True:
  print "tick"
  time.sleep(60.0 - ((time.time() - starttime) % 60.0))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow