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时MySQLdb报错的问题描述及解决方法

问题描述: windows安装python mysqldb时报错python version 2.7 required,which was not found in the regist...

python实现可变变量名方法详解

如果要写一个程序,让x1为1,x2为2,然后直到x100为100,你会怎么做? 在C这种静态语言里,变量名这个标识符实际上会被编译器直接翻译成内存地址,所以除了手动设置每个变量的值以外,...

详解django2中关于时间处理策略

详解django2中关于时间处理策略

一、django中数据模型关于时间字段的认识 1、 DateField :可以记录年月日,映射到数据库是 date 类型 2、 DateTimeField :可以记录年月日时分秒,映射到...

python操作excel文件并输出txt文件的实例

如下所示: #coding=utf-8 import os import xlrd #excel文件放置在当前路径 path='model.xls' #打开文件 data=xlrd....

Python实现判断一行代码是否为注释的方法

目前的编辑器大都可以自动检测某一行代码是否为代码行或注释行,但并不太提供代码行/注释行行数的统计,对于大量代码文件的代码行/注释行统计,就更少见一些。本篇文章试用一段Python脚本来实...