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

yipeiwu_com6年前Python基础

这篇文章主要介绍了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")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pytorch 中pad函数toch.nn.functional.pad()的用法

pytorch 中pad函数toch.nn.functional.pad()的用法

padding操作是给图像外围加像素点。 为了实际说明操作过程,这里我们使用一张实际的图片来做一下处理。 这张图片是大小是(256,256),使用pad来给它加上一个黑色的边框。具体代...

Python实现MySQL操作的方法小结【安装,连接,增删改查等】

本文实例讲述了Python实现MySQL操作的方法。分享给大家供大家参考,具体如下: 1. 安装MySQLdb.从网站下载Mysql for python 的package 注意有32位...

解读python logging模块的使用方法

1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点:...

python对数组进行反转的方法

本文实例讲述了python对数组进行反转的方法。分享给大家供大家参考。具体实现方法如下: arr = [1,2,3] arr.reverse() print(arr) 输出:...

Pandas0.25来了千万别错过这10大好用的新功能

Pandas0.25来了千万别错过这10大好用的新功能

呆鸟云:“7 月 18 日,Pandas 团队推出了 Pandas 0.25 版,这就相当于 Python 3.8 啦,Python 数据分析师可别错过新版的好功能哦。” 安装 0.2...