網站首頁 編程語言 正文
基于signal模塊實現
signal包負責在Python程序內部處理信號,典型的操作包括預設信號處理函數,暫停并等待信號,以及定時發出SIGALRM等。
要注意,signal包主要是針對UNIX平臺(比如Linux, MAC OS),而Windows內核中由于對信號機制的支持不充分,所以在Windows上的Python不能發揮信號系統的功能。?
# coding:utf8
import time
import signal
?
?
# 自定義超時異常
class TimeoutError(Exception):
? ? def __init__(self, msg):
? ? ? ? super(TimeoutError, self).__init__()
? ? ? ? self.msg = msg
?
?
def time_out(interval, callback):
? ? def decorator(func):
? ? ? ? def handler(signum, frame):
? ? ? ? ? ? raise TimeoutError("run func timeout")
?
? ? ? ? def wrapper(*args, **kwargs):
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? signal.signal(signal.SIGALRM, handler)
? ? ? ? ? ? ? ? signal.alarm(interval) ? ? ? # interval秒后向進程發送SIGALRM信號
? ? ? ? ? ? ? ? result = func(*args, **kwargs)
? ? ? ? ? ? ? ? signal.alarm(0) ? ? ? ? ? ? ?# 函數在規定時間執行完后關閉alarm鬧鐘
? ? ? ? ? ? ? ? return result
? ? ? ? ? ? except TimeoutError, e:
? ? ? ? ? ? ? ? callback(e)
? ? ? ? return wrapper
? ? return decorator
?
?
def timeout_callback(e):
? ? print(e.msg)
?
?
@time_out(2, timeout_callback)
def task1():
? ? print("task1 start")
? ? time.sleep(3)
? ? print("task1 end")
?
?
@time_out(2, timeout_callback)
def task2():
? ? print("task2 start")
? ? time.sleep(1)
? ? print("task2 end")
?
?
if __name__ == "__main__":
? ? task1()
? ? task2()
輸出:
?task1 start
?run func timeout
?task2 start
?task2 end
基于子線程阻塞實現超時
# coding:utf8
import time
import threading
?
?
def callback_func():
? ? print('超時回調')
?
?
def time_out(interval, callback=None):
? ? def decorator(func):
? ? ? ? def wrapper(*args, **kwargs):
? ? ? ? ? ? t =threading.Thread(target=func, args=args, kwargs=kwargs)
? ? ? ? ? ? t.setDaemon(True) ?# 設置主線程技術子線程立刻結束
? ? ? ? ? ? t.start()
? ? ? ? ? ? t.join(interval) ?# 主線程阻塞等待interval秒
? ? ? ? ? ? if t.is_alive() and callback:
? ? ? ? ? ? ? ? return threading.Timer(0, callback).start() ?# 立即執行回調函數
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? return
? ? ? ? return wrapper
? ? return decorator
?
?
@time_out(2, callback_func)
def task3(hh):
? ? print('**********task3****************')
? ? for i in range(3):
? ? ? ? time.sleep(1)
? ? ? ? print(i)
? ? ? ? print(hh)
?
?
@time_out(2, callback_func)
def task4(hh):
? ? print('**********task4****************')
? ? for i in range(3):
? ? ? ? # time.sleep(1)
? ? ? ? print(i)
? ? ? ? print(hh)
?
?
if __name__ == '__main__':
? ? task3('參數')
? ? task4('參數')
輸出:
**********task3****************
0
參數
1
參數
超時回調
**********task4****************
0
參數
1
參數
2
參數
基于協程實現
def callback_func():
? ? print('callback')
?
?
def time_out(interval, callback=None):
? ? def decorator(func):
? ? ? ? def wrapper(*args, **kwargs):
? ? ? ? ? ? ########## 該部分必選在requests之前導入
? ? ? ? ? ? import gevent
? ? ? ? ? ? from gevent import monkey
? ? ? ? ? ? monkey.patch_all()
? ? ? ? ? ? ##########
? ? ? ? ? ??
? ? ? ? ? ? try:
? ? ? ? ? ? ? ? gevent.with_timeout(interval, func, *args, **kwargs)
? ? ? ? ? ? except gevent.timeout.Timeout as e:
? ? ? ? ? ? ? ? callback() if callback else None
?
? ? ? ? return wrapper
?
? ? return decorator
?
?
@time_out(3, callback_func)
def func(a, b):
? ? import time
? ? time.sleep(2)
? ? print(a,b)
?
?
func(1, 2)
原文鏈接:https://blog.csdn.net/weixin_42368421/article/details/101354628
相關推薦
- 2023-06-21 Docker安裝部署Redis數據庫的實現步驟_docker
- 2023-01-03 Qt學習之容器類的使用教程詳解_C 語言
- 2022-07-21 SpringCache 面向注解開發
- 2022-09-18 詳解React?hooks組件通信方法_React
- 2022-11-06 ASP.NET?MVC使用Log4Net記錄異常日志并跳轉到靜態頁_實用技巧
- 2023-10-17 npm ERR! code ELIFECYCLE解決方案,npm犯錯!myweb@1.0.0構建腳本
- 2022-03-25 .NET提取?Thread?中返回值詳情_ASP.NET
- 2022-08-06 Go語言開發編程規范命令風格代碼格式_Golang
- 最近更新
-
- 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同步修改后的遠程分支