Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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.

I need something like this would work

while True: 

# Code executed here 

time.sleep(60)

Are there any foreseeable problems with this code?

1 Answer

0 votes
by (106k points)

The best way to repeatedly execute a function every x seconds in Python is to just lock your time loop to the system clock. Easy.

import time 

starttime=time.time() 

while True: 

print "tick" 

time.sleep(60.0 - ((time.time() - starttime) % 60.0))

For more information, kindly refer to our Python Certification course. 

Browse Categories

...