thread入门

文章介绍了Python中使用threading模块创建线程,特别是如何利用Timer实现单次和重复定时任务。通过重写Timer的run方法,创建了RepeatTimer类,能按指定间隔重复执行任务,示例展示了其工作原理。
摘要由CSDN通过智能技术生成

使用语言:python

多线程,例如计网传输的sender需要同时receive和send,这就是thread

thread.Timer,倒计时器,只执行一次

期间可以.cancel()

thread.Threading(, , )这个是一直执行

期间不可以.cancel()

要取消只能在其调用的函数里面加入while var,用variable控制

obj = 上述命令 这是创建对象

obj.start() 这是开始改副线程

Threading是一段时间内一直,Timer是一段时间内一次,这就是区别,

那有没有办法规定一段时间内运行多次呢?难道要由多个一次定时器做成?

重写Timer的run方法,可以解决这个问题

import time
from threading import Timer

def fun_timer():
    print('hello timer', time.time() )

class RepeatTimer(Timer):
    def run(self):                                    
        while not self.finished.wait(self.interval):  
            self.function(*self.args, **self.kwargs)

re = RepeatTimer(1, fun_timer)
re.start()
time.sleep(5) # 运行五秒后主线程苏醒
re.cancel()  # 副线程cancel
Output:

hello timer 1682564123.9084446
hello timer 1682564124.9197044
hello timer 1682564125.930051
hello timer 1682564126.9363446

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值