tags:

views:

454

answers:

5

What would be the most pythonic way to schedule a function to run periodically as a background task? There are some ideas here, but they all seem rather ugly to me. And incomplete.

The java Timer class has a very complete solution. Anyone know of a similar python class?

+1  A: 

There is a handy event scheduler that might do what you need. Here's a link to the documentation:

http://docs.python.org/library/sched.html

dborba
+3  A: 

Many programmers try to avoid multi-threaded code, since it is highly bug-prone in imperative programming.

If you want to a scheduled task in a single-threaded environment, then you probably need some kind of "Reactor". You may want to use a ready-made one like Twisted's.

Then it would be a basic function provided by your reactor, for example (with pygame):

pygame.time.set_timer - repeatedly create an event on the event queue

yairchu
+1  A: 

Python has a Timer class in threading module but that is one-shot timer, so you would be better doing something as you have seen links. http://code.activestate.com/recipes/65222/

Why do you think that is ugly, once you have written such a class usage will be as simple as in java.

if you are using it inside some GUI e.g. wxPython than it has wx.Timer which you can directly use

Anurag Uniyal
+3  A: 

Not direct response to the question.

On Linux/Unix operating system there are few ways to do so and usually I just write my program / script normally and then add it to cron or something similar.

Response to the question starts here.

Use standard python sched module - standard library documentation describes some nifty solutions.

zeroDivisible
+1: Use cron -- it works.
S.Lott
+1  A: 

try the multiprocessing module.

from multiprocessing import Process
import time

def doWork():
    while True:
        print "working...."
        time.sleep(10)



if __name__ == "__main__":
    p = Process(target=doWork)
    p.start()

    while True:
        time.sleep(60)
Tom Willis