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

相关文章

浅谈function(函数)中的动态参数

我们可向函数传递动态参数,*args,**kwargs,首先我们来看*args,示例如下: 1.show(*args) def show(*args): print(args,typ...

浅析PyTorch中nn.Linear的使用

浅析PyTorch中nn.Linear的使用

查看源码 Linear 的初始化部分: class Linear(Module): ... __constants__ = ['bias'] def __init__(s...

numpy linalg模块的具体使用方法

最近在看机器学习的 LogisticRegressor,BayesianLogisticRegressor算法,里面得到一阶导数矩阵g和二阶导数Hessian矩阵H的时候,用到...

Python中修改字符串的四种方法

在Python中,字符串是不可变类型,即无法直接修改字符串的某一位字符。  因此改变一个字符串的元素需要新建一个新的字符串。 常见的修改方法有以下4种。 方法1:将字符串转...

利用python和ffmpeg 批量将其他图片转换为.yuv格式的方法

由于跑编码的需要,所以需要制作一个.yuv格式的图片数据集,但是手头只有.jpg格式的,故记录下转换过程。其他图片格式也可以,代码里修改一下就行。 ①安装ffmpeg 官网(各种版本):...