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
time.sleep(60)
Are there any foreseeable problems with this code?
e.g., Display current local time
You might want to consider Twisted which is a Python networking library that implements the Reactor Pattern.
While "while True: sleep(60)" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution
If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/Network intensive tasks.
Here's the code I've posted in a similar question, with start() and stop() control:
Usage:
Features:
start()
andstop()
are safe to call multiple times even if the timer has already started/stoppedinterval
anytime, it will be effective after next run. Same forargs
,kwargs
and evenfunction
!If you want to do this without blocking your remaining code, you can use this to let it run in its own thread:
This solution combines several features rarely found combined in the other solutions:
threading.Timer
or whatever), this will terminate the chain. No further executions will happen then, even if the reason of the problem is already fixed. A simple loop and waiting with a simplesleep()
is much more robust in comparison.next_time += delay
instead.The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.
The easier way I believe to be:
This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc... No need to complicate things :D