Python timer定時(shí)器兩種常用方法解析
這篇文章主要介紹了Python timer定時(shí)器兩種常用方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
方法一,使用線程中現(xiàn)成的:
這種一般比較常用,特別是在線程中的使用方法,下面是一個(gè)例子能夠很清楚的說(shuō)明它的具體使用方法:
#! /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'))
方法二,根據(jù)time中的來(lái)定義timer:
這種方法使用比較靈活,可根據(jù)自身的東西來(lái)添自身的需求:
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")
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Python中數(shù)據(jù)庫(kù)管理模塊shelve和dbm的應(yīng)用
作為常用的 python 自帶數(shù)據(jù)庫(kù)管理模塊,shelve 和 dbm 都是非常方便的對(duì)象持久化存儲(chǔ)和檢索工具,本文將從用法、優(yōu)勢(shì)以及不同點(diǎn)等方面進(jìn)行介紹,希望對(duì)大家有所幫助2023-10-10Python實(shí)現(xiàn)時(shí)間序列可視化的方法
matplotlib庫(kù)是一個(gè)用于創(chuàng)建出版質(zhì)量圖表的桌面繪圖包(2D繪圖庫(kù)),是Python中最基本的可視化工具。這篇文章主要介紹了Python時(shí)間序列可視化實(shí)現(xiàn),需要的朋友可以參考下2019-08-08在Python中使用MySQL--PyMySQL的基本使用方法
PyMySQL 是在 Python3.x 版本中用于連接 MySQL 服務(wù)器的一個(gè)庫(kù),Python2中則使用mysqldb。這篇文章主要介紹了在Python中使用MySQL--PyMySQL的基本使用,需要的朋友可以參考下2019-11-11Python交互環(huán)境下打印和輸入函數(shù)的實(shí)例內(nèi)容
在本篇文章里小編給大家分享的是關(guān)于Python交互環(huán)境下打印和輸入函數(shù)的實(shí)例內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2020-02-02Matlab如何實(shí)現(xiàn)矩陣復(fù)制擴(kuò)充
這篇文章主要介紹了使用Matlab實(shí)現(xiàn)矩陣復(fù)制擴(kuò)充的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06