日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python中threading.Timer()定時器實現定時任務_python

作者:IT之一小佬 ? 更新時間: 2023-03-17 編程語言

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

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

1、單線程執行

示例代碼:

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()

運行結果:

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

sys.setrecursionlimit(100000000)

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

2、多線程執行

示例代碼:

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()

運行結果:

原文鏈接:https://blog.csdn.net/weixin_44799217/article/details/128667888

欄目分類
最近更新