Python timer定时器两种常用方法解析
这篇文章主要介绍了Pythontimer定时器两种常用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
方法一,使用线程中现成的:
这种一般比较常用,特别是在线程中的使用方法,下面是一个例子能够很清楚的说明它的具体使用方法:
#!/usr/bin/python3
#!-*-conding:utf-8-*-
importthreading
importtime
deffun_timer():
print(time.strftime('%Y-%m-%d%H:%M:%S'))
globaltimer
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:
这种方法使用比较灵活,可根据自身的东西来添自身的需求:
importtime
classTimerError(Exception):
"""AcustomexceptionusedtoreporterrorsinuseofTimerclass"""
classTimer:
def__init__(self):
self._start_time=None
defstart(self):
"""Startanewtimer"""
ifself._start_timeisnotNone:
raiseTimerError(f"Timerisrunning.Use.stop()tostopit")
self._start_time=time.perf_counter()
defstop(self):
"""Stopthetimer,andreporttheelapsedtime"""
ifself._start_timeisNone:
raiseTimerError(f"Timerisnotrunning.Use.start()tostartit")
elapsed_time=time.perf_counter()-self._start_time
self._start_time=None
print(f"Elapsedtime:{elapsed_time:0.4f}seconds")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。