tags:

views:

1037

answers:

3

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?

+9  A: 

Use the sched module

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

s.enter(60, 1, do_something, (s,))
s.run()
nosklo
The sched module is for scheduling functions to run after some time, how do you use it to repeat a function call every x seconds without using time.sleep()?
Baishampayan Ghose
@Baishampayan: Just schedule a new run.
nosklo
Kronos, based on sched, offers a higher level interface: http://www.razorvine.net/download/kronos.py Used by TurboGears.
Alabaster Codify
+2  A: 

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.

bobince
+4  A: 

You might want to consider Twisted which is a python networking library that implements the Reactor Pattern.

from twisted.internet import task
from twisted.internet import reactor

timeout = 60.0 # Sixty seconds

def doWork():
    #do work here
    pass

l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds

reactor.run()

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

Aaron Maenpaa
I knew Twisted could do this. Thanks for sharing the example code!
Baishampayan Ghose