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

yipeiwu_com5年前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设计】。

相关文章

在Python中使用SQLite的简单教程

SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。...

Python入门篇之字符串

所有标准的序列操作对字符串都适用,但字符串是不可变的 字符串常量: 单引号:‘spa"m' 双引号:"spa'm" 三引号:'''...spam...''',"""...spam..."...

python二维码操作:对QRCode和MyQR入门详解

python二维码操作:对QRCode和MyQR入门详解

python是所有编程语言中模块最丰富的 生活中常见的二维码功能在使用python第三方库来生成十分容易 三个大矩形是定位图案,用于标记二维码的大小。这三个定位图案有白边,通过这三个矩...

pandas DataFrame数据转为list的方法

首先使用np.array()函数把DataFrame转化为np.ndarray(),再利用tolist()函数把np.ndarray()转为list,示例代码如下: # -*- co...

python实现比较文件内容异同

本文实例为大家分享了python实现比较文件内容异同的具体代码,供大家参考,具体内容如下 import sys import difflib import time import o...