当前位置: 移动技术网 > IT编程>脚本编程>Python > python中timer定时器常用的两种实现方法

python中timer定时器常用的两种实现方法

2020年03月27日  | 移动技术网IT编程  | 我要评论

峰峰矿区,波动少女下载,columns.add

方法一,使用线程中现成的:

这种一般比较常用,特别是在线程中的使用方法,下面是一个例子能够很清楚的说明它的具体使用方法:

#! /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")

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网