Python 多线程编程-06-threading 模块 - Timer

目   录

1 threading.Timer

1.1 threading.Timer 构造

1.1.1 threading.Timer 构造函数

1.1.2 参数列表

1.2 threading.Timer 属性和方法

1.3 threading.Timer 使用示范

1.3.1 简单延迟调用

1.3.2 当作定时器调用

1.3.3 循环调用比同时起一批线程的优越性


Python 多线程编程目录

Python 多线程编程-01-threading 模块初识

Python 多线程编程-02-threading 模块-锁的使用

Python 多线程编程-03-threading 模块 - Condition

Python 多线程编程-04-threading 模块 - Event

Python 多线程编程-05-threading 模块 - Semaphore 和 BoundedSemaphore

Python 多线程编程-06-threading 模块 - Timer  

Python 多线程编程-07-threading 模块 - Barrier

1 threading.Timer

     threading.Timer 是 threading.Thread 的一个派生类,是在指定的时间 n 秒后执行一个函数功能。它会集成 threading.Thread 的很多属性和方法。

      Timer的源码实现很简单,收到一个任务后,则创建一个线程,线程逻辑里面最前面插入sleep。如果大家仔细想想,在任务非常多时候,上下文切换也是一个很消耗资源的事情,能不用就不用。

1.1 threading.Timer 构造

1.1.1 threading.Timer 构造函数

        timer=threading.Timer(interval, function, args=None, kwargs=None)

1.1.2 参数列表

  1. interval:以秒为单位,指示该线程过多久启动
  2. function:指示该线程要调用什么函数,执行什么功能
  3. args:适用于 function 的参数列表
  4. kwargs:适用于 function 的参数字典

1.2 threading.Timer 属性和方法

        基本上  threading.Thread 的属性和方法, threading.Timer 都有,具体请参看先前的文章 Python 多线程编程-01-threading 模块初识 2.1.1 小节

        除此之外,它还有些特殊的方法。

threading.Timer 属性和方法
序号属性和方法描述
1属性 args适用于 function 的参数列表
2属性 interval以秒为单位,指示该线程过多久启动
3属性 kwargs适用于 function 的参数字典
4方法 stop()如果这个 Timer 还没有结束,则结束之。

        此外一个 threading.Timer 对象,如果调用 .finished() 方法,则是得到一个 threading.Event 类对象。 

1.3 threading.Timer 使用示范

1.3.1 简单延迟调用

下面是一段代码,我希望能依次打印出 words 列表中的 word,每个线程延迟时间取决于 word 的长度,并且每次打印 word 之前先打印当前时间。

import threading
import time
words=["a","12","你好!","春风十里"]
timer_list=[]

def show_time_on_word(word):
    print(time.ctime()+"==>"+word)
    
for word in words:
    timer=threading.Timer(len(word)*10,show_time_on_word,args=[word])
    timer_list.append(timer)

for timer in timer_list:
    timer.start()

运行结果如下:

1.3.2 当作定时器调用

希望运行一段代码,每隔 10 秒报时,累计报时 10 次。

import threading
import time
count=0

def show_time():
    print("Coming in show time!")
    global count
    if(count<10):
        count+=1
        print(time.ctime())
        create_timer()
    else:
        print("All done!")
    
def create_timer():
    timer=threading.Timer(10,show_time)
    timer.start()
    
print(time.ctime()," Starting !")
create_timer()

运行结果

  

1.3.3 循环调用比同时起一批线程的优越性

1.3.2 主要是循环调用生成 Timer,而1.3.1 则是同时生成一批线程。相比较而言,循环调用更好,通过调用 threading.active_count() 可以看出,此时不会需要多维护线程。

'''

要是大家觉得写得还行,麻烦点个赞或者收藏吧,想个博客涨涨人气,非常感谢!

'''

  • 17
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南野栀子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值