對python周期性定時器的示例詳解
更新時間:2019年02月19日 15:41:57 作者:橘子or桔子
今天小編就為大家分享一篇對python周期性定時器的示例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
一、用thread實(shí)現(xiàn)定時器
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周期性定時器的示例詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決django中form表單設(shè)置action后無法回到原頁面的問題
這篇文章主要介紹了解決django中form表單設(shè)置action后無法回到原頁面的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03詳解pandas中利用DataFrame對象的.loc[]、.iloc[]方法抽取數(shù)據(jù)
這篇文章主要介紹了pandas中利用DataFrame對象的.loc[]、.iloc[]方法抽取數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12教你一步步利用python實(shí)現(xiàn)貪吃蛇游戲
這篇文章主要給大家介紹了關(guān)于如何利用python實(shí)現(xiàn)貪吃蛇游戲的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06