python 定时器

来源:互联网 发布:java调用存储过程 编辑:程序博客网 时间:2024/05/01 09:47

1. Timer

def hello(name):    print 'hello world, i am %s, Current time: %s' % (name, time.time()) hello = partial(hello, 'guo')  t = Timer(3, hello)t.start()

但是只执行一次,想办法做成一个真正的定时器:

def hello(name):    global t    t = Timer(3, hello)    t.start()    print 'hello world, i am %s, Current time: %s' % (name, time.time())  hello = partial(hello, 'guo')  t = Timer(3, hello)t.start()

2. sched

def hello(name):    print 'hello world, i am %s, Current Time:%s' % (name, time.time())s = sched.scheduler(time.time, time.sleep)s.enter(3, 2, hello, ('guo',))s.run()

和Timer是一样的效果,再修改:

def hello(name):    print 'hello world, i am %s, Current Time:%s' % (name, time.time())    run(name)    def run(name):    s = sched.scheduler(time.time, time.sleep)    s.enter(3, 2, hello, (name,))    s.run()    s = sched.scheduler(time.time, time.sleep)s.enter(3, 2, hello, ('guo',))s.run()

3. threading

repeatTimer.py

from threading import Event, Thread class RepeatTimer(Thread):    def __init__(self, interval, function, iterations=0, args=[], kwargs={}):        Thread.__init__(self)        self.interval = interval        self.function = function        self.iterations = iterations        self.args = args        self.kwargs = kwargs        self.finished = Event()     def run(self):        count = 0        while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations):            self.finished.wait(self.interval)            if not self.finished.is_set():                self.function(*self.args, **self.kwargs)                count += 1     def cancel(self):        self.finished.set()

def hello(name):    print 'hello world, i am %s, Current Time:%s' % (name, time.time()) hello = partial(hello, 'guo')#r = RepeatTimer(5.0, hello, 3)r = RepeatTimer(5.0, hello)r.start()

4. sleep

当然最简单的办法还是循环+sleep:

def hello(name):    print 'hello world, i am %s, Current Time:%s' % (name, time.time())    if __name__=='__main__':    while True:        hello('guo')        sleep(3)
不过这样看起来太不专业了。。

5. 如果是大型项目中需要用到定时或周期做某个事情,前面所说的就有点不太敬业了

推荐:celeryd+rabbitmq,很强大


--------------------------

感谢:http://g-off.net/software/a-python-repeatable-threadingtimer-class

            http://www.coder4.com/archives/1589

原创粉丝点击