Run A Task At Specific Intervals In Python
Solution 1:
There is a handy event scheduler that might do what you need. Here's a link to the documentation:
Solution 2:
try the multiprocessing module.
from multiprocessing import Process
import time
defdoWork():
whileTrue:
print"working...."
time.sleep(10)
if __name__ == "__main__":
p = Process(target=doWork)
p.start()
whileTrue:
time.sleep(60)
Solution 3:
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
Solution 4:
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 (like launchd on OS X)
Response to the question starts here.
Use standard python sched module - standard library documentation describes some nifty solutions.
Solution 5:
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
Post a Comment for "Run A Task At Specific Intervals In Python"