這篇文章給大家介紹使用python怎么實現一個周期性定時器,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

Python是一種編程語言,內置了許多有效的工具,Python幾乎無所不能,該語言通俗易懂、容易入門、功能強大,在許多領域中都有廣泛的應用,例如最熱門的大數據分析,人工智能,Web開發等。
一、用thread實現定時器
py_timer.py文件
#!/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()二、 使用
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怎么實現一個周期性定時器就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網站標題:使用python怎么實現一個周期性定時器-創新互聯
本文鏈接:http://www.yijiale78.com/article46/dpsgeg.html
成都網站建設公司_創新互聯,為您提供定制開發、品牌網站建設、外貿建站、虛擬主機、做網站、網頁設計公司
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯