当前位置: 移动技术网 > IT编程>脚本编程>Python > Python timer定时器两种常用方法解析

Python timer定时器两种常用方法解析

2020年03月09日  | 移动技术网IT编程  | 我要评论

冯媛甑,香港三圾片排行榜,新天生一对下载

这篇文章主要介绍了python timer定时器两种常用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

方法一,使用线程中现成的:

这种一般比较常用,特别是在线程中的使用方法,下面是一个例子能够很清楚的说明它的具体使用方法:

#! /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:

这种方法使用比较灵活,可根据自身的东西来添自身的需求:

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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网