如何在Python中执行线程定时器
线程允许多个任务同时运行。例如,当任务A正在运行时,我不必等待它完成。同时,任务B、C也会运行。当任务同时运行时,它们需要多个CPU。
为了并发地运行线程,Python使用了一种被称为任务切换的技术。结果是,Python在每个任务之间快速切换。使得它看起来像是多个任务在并行运行,使得它在事件驱动的任务中很有用。线程是轻量级的,它需要更少的内存,从而节省CPU资源。
如何在Python中执行线程定时器
一个线程有一个入口,一个执行点和一个退出点。Python库包含一个定时器,它是**"线程 "**类的一个子类,用于在限定的时间内执行代码。
Python中的线程 Timer()在定义为参数的延迟后开始。因此,定时器类调用自己,使下面的操作延迟执行,延迟的时间与指定的时间相同。
先决条件
要想继续学习,读者需要具备以下条件。
- 一些Python的基础知识。
Python定时器函数
每隔指定的秒数后,就会调用一个定时器类的函数。start()是一个用于初始化定时器的函数。要结束或退出定时器,必须使用cancel()函数。为了使用线程类,导入线程类是必要的。使用函数time.sleep(secs)可以使调用的线程暂停数秒。
- 为了更好地理解这一点,我将用一个代码片断和预期的输出截图来说明它。
实例1
py
代码解读
复制代码
## How class threading.Timer() in python works
import threading as th
## Defining a method
def sctn():
print("SECTION FOR LIFE \n")
S = th.Timer(5.0, sctn)
S.start()
print("Exit Program\n")
- 代码运行后,需要5分钟才能显示
SECTION FOR LIFE
。
实例2
在第二个例子中,我将向你展示如何实现暂停方法cancel()
,我们在前面已经看到它是为了结束一个线程。
py
代码解读
复制代码
##Illustrating the use of cancel() method in class Timer.
import threading as th
## Defining of a method
def sctn():
print("SECTION FOR LIFE \n")
S = th.Timer(5.0, sctn)
S.start()
print("PROGRAM TERMINATION\n")
S.cancel()
- 当程序被执行时,显示的是PROGRAM TERMINATION一行。这是因为对象th.Timer在执行**"sctn "**函数之前就被取消了。
- 下面是上述程序的输出。
线程模块概述
最新的线程模块包含在当前的Python 2.4中,与之前的线程模块相比,它对线程提供了更强大、更高级别的支持。
线程模块暴露了线程模块的所有方法,并提供了一些额外的功能,如下图所示。
bash
代码解读
复制代码
thread.activeCount() − Returns how many thread objects are active.
thread.currentThread() − Returns how many thread objects in the caller's thread control.
thread.enumerate() − Returns an overview list of all thread objects that are currently active.
创建和使用定时器类
线程的美妙之处在于,你可以告诉计算机在其他时间执行一项任务,或者同时进行。你还可以在不同的线程上同时执行代码,这使它变得非常强大。一个定时器类总是以间隔方式运行。
Python Timer 类用于执行一个操作或在指定的时间段过后让一个函数运行。线程类有一个子类,叫做类Timer。从技术角度讲,当我们需要有时间限制的操作(方法)时,我们将创建Timer对象。
要使用Timer类,我们首先要导入时间模块。args参数总是最好用来声明要调用的函数的参数。
py
代码解读
复制代码
##Timers
##Execute code at timed intervals
##Imports and Displays
import time
from threading import Timer
def display(msg):
print(msg + ' ' + time.strftime('%H:%M:%S'))
##Basic timer
def run_once():
display('run_once:')
t=Timer(10,display,['Timeout:'])
t.start()#Here run is called
run_once()
##Runs immediately and once
print('Waiting.....')
##Lets make our timer run in intervals
##Put it into a class
##Making it run until we stop it
##Just getting crazy.Notice We have multiple timers at once!
class RepeatTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args,**self.kwargs)
print(' ')
##We are now creating a thread timer and controling it
timer = RepeatTimer(1,display,['Repeating'])
timer.start() #recalling run
print('Threading started')
time.sleep(10)#It gets suspended for the given number of seconds
print('Threading finishing')
timer.cancel()
- 下面是输出结果。
与Python装饰器一起工作
在使用Python装饰器工作时,将知道如何扩展Python Timer以使其被重复使用。使用装饰器的重要性在于,它只被实现一次,而函数每次都被计时。
- 首先,我们将让Python定时器在装饰函数之前被调用,在调用结束后,终止Python定时器。
py
代码解读
复制代码
import functools
import time
def timer(meth):
@functools.wraps(meth)
def timer_container(*args, **kwargs):
click = time.flow()
value: object = meth(*args, **kwargs)
clock = time.flow()
time_passed = click - clock ##getting the time spent
print(f"TIME PASSED IS: {time_passed:0.2f} SECS") ##displaying time passed to 2 decimal places
return value
return timer_container()
当代码运行时,输出应该是。
bash
代码解读
复制代码
TIME PASSED IS: 0.59 SECS
使用线程的重要性
- 线程可以并发操作,多线程程序可以在有多个CPU的计算机系统上运行得更快。
- 一个程序可以继续对输入作出反应。这在单个CPU以及多个CPU上都是如此。
- 一个进程中的线程可以共享全局变量内存。当一个全局变量在一个线程中被修改时,它会影响到所有线程。本地变量也可以存在于一个线程中。
- 在操作系统中处理线程比处理进程要容易。因此,它们有时被称为轻量级进程。
- 它可以被中断,因此允许高优先级的进程。
- 它可以在其他线程运行时暂时搁置(有时被称为睡眠模式)--这被称为屈服。
总结
在这篇文章中,我们已经学到了以下内容。
- Python定时器函数。如何使用诸如cancel()这样的函数来停止执行,甚至在它开始之前。
- 创建和使用定时器类。计时器类是线程类的一个子类。
- 使用Python装饰器。装饰器只用一次,但函数会被不断地计时。