Python实现高精度可调节定时器

陆遥
陆遥
发布时间:2026-10-13| 5人浏览过
原创

本文介绍了一种基于Python实现的定时器程序,支持通过命令行参数指定延时时间(毫秒级)。程序利用getopt解析参数,并通过threading模块实现非阻塞定时功能,适用于需要精确控制执行时长的场景。

本文分享了一个使用Python编写的定时器示例,该定时器允许用户调节定时精度,供读者参考。

# -* coding: utf-8 -*- 
 
import sys 
import os 
import getopt 
import threading 
import time 
 
def Usage(): 
  usage_str = '''''说明: 
  \t定时器 
  \timer.py -h 显示本帮助信息,也可以使用--help选项 
  \timer.py -d num 指定一个延时时间(以毫秒为单位) 
  \t          也可以使用--duration=num选项 
  ''' 
  print(usage_str) 
   
   
def args_proc(argv): 
  '''''处理命令行参数''' 
  try: 
    opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'duration=']) 
  except getopt.GetoptError as err: 
    print('错误!请为脚本指定正确的命令行参数。\n') 
    Usage() 
    sys.exit(255) 
     
  if len(opts) < 1: 
    print('使用提示:缺少必须的参数。') 
    Usage() 
    sys.exit(255) 
     
  usr_argvs = {} 
  for op, value in opts: 
    if op in ('-h', '--help'): 
      Usage() 
      sys.exit(1) 
    elif op in ('-d', '--duration'): 
      if int(value) <= 0: 
        print('错误!指定的参数值%s无效。\n' % (value)) 
        Usage() 
        sys.exit(2) 
      else: 
        usr_argvs['-d'] = int(value) 
    else: 
      print('unhandled option') 
      sys.exit(3) 
 
  return usr_argvs 
   
def timer_proc(interval_in_millisecond): 
  loop_interval = 10   # 定时精度,也是循环间隔时间(毫秒),也是输出信息刷新间隔时间,它不能大于指定的最大延时时间,否则可能导致无任何输出 
  t = interval_in_millisecond / loop_interval 
  while t >= 0: 
    min = (t * loop_interval) / 1000 / 60 
    sec = (t * loop_interval) / 1000 % 60 
    millisecond = (t * loop_interval) % 1000 
    print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t') 
    time.sleep(loop_interval / 1000) 
    t -= 1 
  if millisecond != 0: 
    millisecond = 0 
    print('\rThe remaining time:%02d:%02d:%03d...' % ( min, sec, millisecond ), end = '\t\t') 
  print() 
   
# 应用程序入口 
if __name__ == '__main__': 
  usr_argvs = {} 
  usr_argvs = args_proc(sys.argv) 
  for argv in usr_argvs: 
    if argv in ( '-d', '--duration'): 
      timer_proc(usr_argvs[argv]) 
    else: 
      continue 

以上就是本文的全部内容,希望对读者的学习有所帮助,同时也欢迎大家继续支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

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 算法库。