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利用Beautiful Soup模块搜索内容详解

前言 我们将利用 Beautiful Soup 模块的搜索功能,根据标签名称、标签属性、文档文本和正则表达式来搜索。 搜索方法 Beautiful Soup 内建的搜索方法如下:...

Python中join和split用法实例

join用来连接字符串,split恰好相反,拆分字符串的。 不用多解释,看完代码,其意自现了。 复制代码 代码如下: >>>li = ['my','name','is'...

对numpy中数组元素的统一赋值实例

Numpy中的数组整体处理赋值操作一直让我有点迷糊,很多时候理解的不深入。今天单独列写相关的知识点,进行总结一下。 先看两个代码片小例子: 例子1: In [2]: arr =np....

Python离线安装PIL 模块的方法

Python离线安装PIL 模块的方法

python的库一般都用pip安装。 但是有时候也会出现在线安装失败的情况,如下图安装PIL模块时报错: 这时候可以采取离线安装的方式; 一、首先下载离线安装包 PIL官方版不支持py...

python装饰器decorator介绍

一、装饰器decorator decorator设计模式允许动态地对现有的对象或函数包装以至于修改现有的职责和行为,简单地讲用来动态地扩展现有的功能。其实也就是其他语言中的AOP的概念...