網站首頁 Python教程 正文
threading.Timer
一次timer只生效一次,不會反復循環,如果實現循環觸發,代碼如下:
import time import threading def createTimer(): t = threading.Timer(2, repeat) t.start() def repeat(): print('Now:', time.strftime('%H:%M:%S',time.localtime())) createTimer() createTimer()
這段代碼的功能就是每2秒打印出當前的時間,即一個2秒的定時器。運行效果如下:
E:\py>python timer.py
Now: 16:36:15
Now: 16:36:17
Now: 16:36:19
Now: 16:36:21
Now: 16:36:23
Now: 16:36:25
Now: 16:36:27
cancel函數,可以在定時器被觸發前,取消這個Timer。
允許多個定時任務,并發執行,互不干擾。
如果想更精確地控制定時器函數的觸發時間,就需要把下一次定時器觸發的代碼,放在定時器執行代碼最開始的地方,如下:
import time import threading def createTimer(): t = threading.Timer(2, repeat) t.start() def repeat(): createTimer() print('Now-1:', time.strftime('%H:%M:%S',time.localtime())) time.sleep(3) print('Now-2:', time.strftime('%H:%M:%S',time.localtime())) createTimer()
定時器repeat要執行至少3秒,但是2秒后,下一個定時器就會被觸發,這是允許的!上面這段代碼的執行效果如下:
E:\py>python timer.py
Now-1: 16:46:12
Now-1: 16:46:14
Now-2: 16:46:15
Now-1: 16:46:16
Now-2: 16:46:17
Now-1: 16:46:18
Now-2: 16:46:19
Now-1: 16:46:20
Now-2: 16:46:21
Now-1: 16:46:22
Now-2: 16:46:23
從打印信息來分析,同時存在多個repeat函數的執行序列是沒問題的,這種情況下,還需要認真考慮定時器函數的可重入問題!
以上就是對threading.Timer使用的介紹,請注意兩種設置定時器循環計時開始的方法,以及他們的區別。
總結
原文鏈接:https://blog.51cto.com/u_15067267/3837295
相關推薦
- 2022-03-29 Python雙端隊列實現回文檢測_python
- 2022-05-20 PyQt5實現數據的增刪改查功能詳解_python
- 2022-12-29 Kotlin標準函數與靜態方法應用詳解_Android
- 2022-09-26 車載藍牙PIN碼是什么
- 2023-02-18 go?micro微服務框架項目搭建方法_Golang
- 2022-10-30 Android中二維碼的掃描和生成(使用zxing庫)_Android
- 2022-11-17 Android開發Flutter?桌面應用窗口化實戰示例_Android
- 2022-03-31 如何利用Python實現n*n螺旋矩陣_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支