Python Threading Timer的使用方法

Python Threading Timer的使用方法

介绍python 多线程的Timer使用
repeat function every ‘n’ seconds
用timer连续执行一个function

from threading import Timer,Thread,Event,Lock
import time
import logging


logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-9s) %(message)s',)


class MyThread(Thread):
    def __init__(self, interval, hFunction):
        Thread.__init__(self)
        self.hFunction = hFunction
        # self.stopped = event
        self.interval = interval
        
        # initialize a timer object to execute the function handler
        # this timer will call function handler after [interval] seconds
        self.thread = Timer(self.interval,self.function_handler)
        
    def function_handler(self):
        self.hFunction() # execute the function (the actual function for execution)
        # create a new timer to call the funciton_handler again
        self.thread = Timer(self.interval,self.function_handler)
        self.thread.start()
    
    def start(self):
        self.thread.start() # this will start the first timer
        
    def cancel(self):
        print ('before cancel thread.is_alive() = ', self.thread.is_alive())
        self.thread.cancel() # cancel the timer thread
        print ('after cancel thread.is_alive() = ', self.thread.is_alive())



class Main_class():
    def __init__(self):
        self.count = 0
        self.timer_function = MyThread(1,self.function) # wait 1s to execute function 
        # IMPORTANT: use "self.function" instead of self.function()
        self.timer_function.start()
        
        
    def function(self):
        countLock = Lock() # 若多个线程需要对共享变量进行更改,需要用Lock()方法
        countLock.acquire()
        
        logging.debug('thread function running')
        self.count +=1
        print (self.count)
        
        countLock.release()
    

            
def main():
    logging.debug('starting timers...')
    
    main_class = Main_class()
    
    
    time.sleep(5) # 5秒后停止定时器
    main_class.timer_function.cancel()
            
if __name__ == '__main__':            
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值