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

Python是一種編程語(yǔ)言,內(nèi)置了許多有效的工具,Python幾乎無(wú)所不能,該語(yǔ)言通俗易懂、容易入門(mén)、功能強(qiáng)大,在許多領(lǐng)域中都有廣泛的應(yīng)用,例如最熱門(mén)的大數(shù)據(jù)分析,人工智能,Web開(kāi)發(fā)等。
一、用thread實(shí)現(xiàn)定時(shí)器
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'關(guān)于使用python怎么實(shí)現(xiàn)一個(gè)周期性定時(shí)器就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
網(wǎng)站標(biāo)題:使用python怎么實(shí)現(xiàn)一個(gè)周期性定時(shí)器-創(chuàng)新互聯(lián)
本文鏈接:http://www.chinadenli.net/article46/dpsgeg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開(kāi)發(fā)、品牌網(wǎng)站建設(shè)、外貿(mào)建站、虛擬主機(jī)、做網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容