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计算回文数的方法

本文实例讲述了Python计算回文数的方法。分享给大家供大家参考。具体如下: 这里检查数字是不是回文数,用196算法生成一个数字的回文数 num = 905; def is_Pali...

Python中使用logging模块打印log日志详解

学一门新技术或者新语言,我们都要首先学会如何去适应这们新技术,其中在适应过程中,我们必须得学习如何调试程序并打出相应的log信息来,正所谓“只要log打的好,没有bug解不了”,在我们熟...

Python 装饰器@,对函数进行功能扩展操作示例【开闭原则】

本文实例讲述了Python 装饰器@,对函数进行功能扩展操作。分享给大家供大家参考,具体如下: 装饰器可以对原函数进行功能扩展,但还不需要修改原函数的内容(开闭原则),也不需要修改原函数...

python实现决策树分类

python实现决策树分类

上一篇博客主要介绍了决策树的原理,这篇主要介绍他的实现,代码环境python 3.4,实现的是ID3算法,首先为了后面matplotlib的绘图方便,我把原来的中文数据集变成了英文。 原...

Windows下搭建python开发环境详细步骤

Windows下搭建python开发环境详细步骤

本文为大家分享了Windows下搭建python开发环境详细步骤,供大家参考,具体内容如下 1.搭建Java环境 (1)直接从官网下载相应版本的JDK或者JRE并点击安装就可以 (2)J...