一、用thread实现定时器
py_timer.py文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#!/usr/bin/python #coding:utf-8 import threading import os import sys class _Timer(threading.Thread): def __init__( self , interval, function, args = [], kwargs = {}): threading.Thread.__init__( self ) self .interval = interval self .function = function self .args = args self .kwargs = kwargs self .finished = threading.Event() def cancel( self ): self .finished. set () def run( self ): self .finished.wait( self .interval) if not self .finished.is_set(): self .function( * self .args, * * self .kwargs) self .finished. set () class LoopTimer(_Timer): def __init__( self , interval, function, args = [], kwargs = {}): _Timer.__init__( self , interval, function, args, kwargs) def run( self ): while True : if not self .finished.is_set(): self .finished.wait( self .interval) self .function( * self .args, * * self .kwargs) else : break def testlooptimer(): print ( "loop timer" ) if __name__ = = '__main__' : t = LoopTimer( 3.0 ,testlooptimer) t.start() |
二、 使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import py_timer def serv_start(): #Perform first fork. try : thread_timer = py_timer.LoopTimer(timeout, start_timer) thread_timer.start() thread_timer.cancel() # except Exception, ex: print ( "daemon: %s %s" , type (ex), ex) def start_timer(): print 'hello' |
以上这篇对python周期性定时器的示例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u013827488/article/details/74356795