欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中threading.Timer()定時器實現(xiàn)定時任務

 更新時間:2023年01月18日 16:01:10   作者:IT之一小佬  
本文主要介紹了Python中threading.Timer()定時器實現(xiàn)定時任務,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

timer最基本理解就是定時器,可以啟動多個定時任務,這些定時器任務是異步執(zhí)行,所以不存在等待順序執(zhí)行問題。

Timer方法說明
Timer(interval, function, args=None, kwargs=None)創(chuàng)建定時器
cancel()取消定時器
start()使用線程方式執(zhí)行
join(self, timeout=None)等待線程執(zhí)行結束

1、單線程執(zhí)行

示例代碼:

from datetime import datetime
from threading import Timer
 
 
def task():
    now = datetime.now()
    ts = now.strftime("%Y-%m-%d %H:%M:%S")
    print(ts)
 
 
def func():
    task()
    t = Timer(3, func)
    t.start()
 
 
func()

運行結果:

優(yōu)缺點:可以實現(xiàn)異步任務,是非阻塞的,但當運行次數(shù)過多時,會出現(xiàn)報錯:Pyinstaller maximum recursion depth exceeded Error Resolution 達到最大遞歸深度,然后想到的是修改最大遞歸深度,

sys.setrecursionlimit(100000000)

但是運行到達到最大CPU時,python會直接銷毀程序。

2、多線程執(zhí)行

示例代碼:

from datetime import datetime
from threading import Timer
import threading
 
 
def task():
    now = datetime.now()
    ts = now.strftime("%Y-%m-%d %H:%M:%S")
    print(ts)
 
 
def func():
    task()
    t = Timer(3, func)
    t.start()
 
 
if __name__ == '__main__':
    for i in range(3):
        thread = threading.Thread(None, func)
        thread.start()

運行結果:

 到此這篇關于Python中threading.Timer()定時器實現(xiàn)定時任務的文章就介紹到這了,更多相關threading.Timer()定時器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論