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:

這種方法使用比較靈活,可根據自身的東西來添自身的需求:

'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ羣:579817333 
尋找有志同道合的小夥伴,互幫互助,羣裏還有不錯的視頻學習教程和PDF電子書!
'''
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")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章