Python定时器实例代码


Posted in Python onNovember 01, 2017

在实际应用中,我们经常需要使用定时器去触发一些事件。Python中通过线程实现定时器timer,其使用非常简单。看示例:

import threading
def fun_timer():
  print('Hello Timer!')
timer = threading.Timer(1, fun_timer)
timer.start()

输出结果:

Hello Timer!
Process finished with exit code 0

注意,只输出了一次,程序就结束了,显然不是我们想要的结果。看Timer类中的解释性描述:

"""Call a function after a specified number of seconds"""

一段时间后调用一个函数,但并没有说要循环调用该函数。因此,修改如下:

def fun_timer():
  print('Hello Timer!')
  global timer
  timer = threading.Timer(5.5, fun_timer)
  timer.start()

timer = threading.Timer(1, fun_timer)
timer.start()

输出结果:

Hello Timer!
Hello Timer!
Hello Timer!
Hello Timer!
............

定时器工作正常。

在使用Python定时器时需要注意如下4个方面:

(1)定时器构造函数主要有2个参数,第一个参数为时间,第二个参数为函数名,第一个参数表示多长时间后调用后面第二个参数指明的函数。第二个参数注意是函数对象,进行参数传递,用函数名(如fun_timer)表示该对象,不能写成函数执行语句fun_timer(),不然会报错。用type查看下,可以看出两者的区别。

print(type(fun_timer()))
print(type(fun_timer))

输出:

Hello Timer!
<class 'NoneType'>
<class 'function'>

(2)必须在定时器执行函数内部重复构造定时器,因为定时器构造后只执行1次,必须循环调用。

(3)定时器间隔单位是秒,可以是浮点数,如5.5,0.02等,在执行函数fun_timer内部和外部中给的值可以不同。如上例中第一次执行fun_timer是1秒后,后面的都是5.5秒后执行。

(4)可以使用cancel停止定时器的工作,如下例:

# -*- coding: utf-8 -*-
import threading
import time
def fun_timer():
  print('Hello Timer!')
  global timer
  timer = threading.Timer(5.5, fun_timer)
  timer.start()
timer = threading.Timer(1, fun_timer)
timer.start()
time.sleep(15) # 15秒后停止定时器
timer.cancel()

输出:

Hello Timer!
Hello Timer!
Hello Timer!
Process finished with exit code 0

下面是一个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定时器实例代码的全部内容,希望对大家有所帮助。欢迎参阅:Python生成数字图片代码分享、Python列表删除的三种方法代码分享、13个最常用的Python深度学习库介绍等,有什么问题可以随时留言,欢迎大家交流参考。

Python 相关文章推荐
Windows平台Python连接sqlite3数据库的方法分析
Jul 12 Python
python出现&quot;IndentationError: unexpected indent&quot;错误解决办法
Oct 15 Python
Python实现重建二叉树的三种方法详解
Jun 23 Python
Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例
Jan 23 Python
Python实现简单层次聚类算法以及可视化
Mar 18 Python
深入了解python中元类的相关知识
Aug 29 Python
关于django 1.10 CSRF验证失败的解决方法
Aug 31 Python
python常用数据重复项处理方法
Nov 22 Python
Pytorch 神经网络—自定义数据集上实现教程
Jan 07 Python
python 解决tqdm模块不能单行显示的问题
Feb 19 Python
几款Python编译器比较与推荐(小结)
Oct 15 Python
python操作ini类型配置文件的实例教程
Oct 30 Python
机器学习python实战之决策树
Nov 01 #Python
详解Python开发中如何使用Hook技巧
Nov 01 #Python
python利用标准库如何获取本地IP示例详解
Nov 01 #Python
你眼中的Python大牛 应该都有这份书单
Oct 31 #Python
Python生成数字图片代码分享
Oct 31 #Python
python使用标准库根据进程名如何获取进程的pid详解
Oct 31 #Python
Python列表删除的三种方法代码分享
Oct 31 #Python
You might like
php实现ping
2006/10/09 PHP
不用数据库的多用户文件自由上传投票系统(1)
2006/10/09 PHP
php中Ctype函数用法详解
2014/12/09 PHP
JavaScript与HTML结合的基本使用方法整理
2015/10/12 PHP
/etc/php-fpm.d/www.conf 配置注意事项
2017/02/04 PHP
基于php(Thinkphp)+jquery 实现ajax多选反选不选删除数据功能
2017/02/24 PHP
javascript XML数据显示为HTML一例
2008/12/23 Javascript
Js从头学起(基本数据类型和引用类型的参数传递详细分析)
2012/02/16 Javascript
javascript动画对象支持加速、减速、缓入、缓出的实现代码
2012/09/30 Javascript
可以用鼠标拖动的DIV实现思路及代码
2013/10/21 Javascript
jquery仿百度经验滑动切换浏览效果
2015/04/14 Javascript
jQuery可见性过滤器:hidden和:visibility用法实例
2015/06/24 Javascript
jquery.map()方法的使用详解
2015/07/09 Javascript
网页挂马方式整理及详细介绍
2016/11/03 Javascript
深入理解javascript prototype的相关知识
2019/09/19 Javascript
使用Python判断质数(素数)的简单方法讲解
2016/05/05 Python
读写json中文ASCII乱码问题的解决方法
2016/11/05 Python
numpy实现合并多维矩阵、list的扩展方法
2018/05/08 Python
Python交互环境下实现输入代码
2018/06/22 Python
pyqt5实现按钮添加背景图片以及背景图片的切换方法
2019/06/13 Python
Django执行源生mysql语句实现过程解析
2020/11/12 Python
python中append函数用法讲解
2020/12/11 Python
纯CSS3实现图片无间断轮播效果
2016/08/25 HTML / CSS
基于html和CSS3制作酷炫的导航栏
2015/09/23 HTML / CSS
css3 矩阵的使用详解
2018/03/20 HTML / CSS
欧洲第一中国智能手机和平板电脑网上商店:CECT-SHOP
2018/01/08 全球购物
园林施工员岗位职责
2013/12/11 职场文书
师范院校学生自荐信范文
2013/12/27 职场文书
2014新年寄语
2014/01/20 职场文书
大学同学聚会邀请函
2014/01/29 职场文书
2015幼儿园庆元旦活动方案
2014/12/09 职场文书
搭讪开场白台词大全
2015/05/28 职场文书
化工厂员工工作总结
2015/10/15 职场文书
python scipy 稀疏矩阵的使用说明
2021/05/26 Python
一文搞懂Golang 时间和日期相关函数
2021/12/06 Golang
Zabbix对Kafka topic积压数据监控的问题(bug优化)
2022/07/07 Servers