這篇文章主要介紹了Python timer定時器兩種常用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
方法一,使用線程中現成的:
這種一般比較常用,特別是在線程中的使用方法,下面是一個例子能夠很清楚的說明它的具體使用方法:
#! /usr/bin/python3#! -*- conding: utf-8 -*-import threadingimport timedef 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 timeclass 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")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網之家。
新聞熱點
疑難解答