1. sched
https://docs.python.org/2/library/sched.html
作为一名Linux的SA,我们已经习惯了用crontab,而sched提供了一种延迟处理机制,也可以理解为任务调度的另一种方式的实现。
注意:
sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,请再次enter
run()一直被阻塞,直到所有事件被全部执行完. 每个事件在同一线程中运行,所以如果一个事件的执行时间大于其他事件的延迟时间,那么,就会产生重叠。重叠的解决方法是推迟后来事件的执行时间。这样保证没有丢失任何事件,但这些事件的调用时刻会比原先设定的迟。
从3.3版本开始,scheduler是线程安全的。
举例:
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print "Doing stuff..."
# do you stuff
sc.enter(2, 1, do_something, (sc,))
s.enter(2, 1, do_something, (s,))
s.run()
2. threading.Timer
https://docs.python.org/2/library/threading.html?highlight=timer#timer-objects
Timer 不是循环的,一次调度被执行后就Over了,如果想再执行,请再次enter
举例:
#!/usr/bin/env python
from threading import Timer
from time import sleep
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):