Python实现定时器的两种核心方式:线程Timer与自定义计时器类

花开有时
花开有时
发布时间:2026-10-13 | 5人浏览过
原创

本文深入解析Python中实现定时任务的两种主流方案。第一种基于threading模块的Timer类,适用于多线程环境下的周期性或单次延时执行;第二种通过封装time模块构建自定义Timer类,提供更灵活的计时控制与异常处理机制。文章结合具体代码示例,对比两者在启动、停止及资源管理上的差异,帮助开发者根据实际场景选择最优方案。

本文详细解析Python中两种常用的定时器实现方法,并通过具体代码示例展示其应用细节,旨在为开发者的学习与实践提供具有参考价值的技术指南。

基于threading模块的线程定时器

第一种方法利用Python标准库中现成的线程定时器功能。

该方式在多线程编程场景中应用广泛,以下示例清晰展示了其具体调用流程与执行逻辑:


#! /usr/bin/python3
#! -*- conding: utf-8 -*-
import threading
import time
def fun_timer():
  print(time.strftime('%Y-%m-%d %H:%M:%S'))
  global timer
  timer = threading.Timer(2,fun_timer)
  timer.start();
timer = threading.Timer(1,fun_timer)
timer.start();
time.sleep(5)
timer.cancel()
print(time.strftime('%Y-%m-%d %H:%M:%S'))

基于time模块的自定义Timer类

第二种方法基于time模块自行定义Timer类。

此方案具备较高的灵活性,开发者可根据具体业务需求扩展定制功能。


import time

class TimerError(Exception):
  """A custom exception used to report errors in use of Timer class"""

class Timer:
  def __init__(self):
    self._start_time = None

  def start(self):
    """Start a new timer"""
    if self._start_time is not None:
      raise TimerError(f"Timer is running. Use .stop() to stop it")

    self._start_time = time.perf_counter()

  def stop(self):
    """Stop the timer, and report the elapsed time"""
    if self._start_time is None:
      raise TimerError(f"Timer is not running. Use .start() to start it")

    elapsed_time = time.perf_counter() - self._start_time
    self._start_time = None
    print(f"Elapsed time: {elapsed_time:0.4f} seconds")

以上内容为本文的全部技术分享,希望能为读者的技术积累提供有益帮助,欢迎持续关注与支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表