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

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

本文深入解析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 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。