Run a task at specific intervals in python [duplicate]

 ̄綄美尐妖づ 提交于 2019-12-18 12:18:17

问题


Possible Duplicate:
Suggestions for a Cron like scheduler in Python?

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:


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




回答2:


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)



回答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




回答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.




回答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



来源:https://stackoverflow.com/questions/1038907/run-a-task-at-specific-intervals-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!