網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
基于signal模塊實(shí)現(xiàn)
signal包負(fù)責(zé)在Python程序內(nèi)部處理信號(hào),典型的操作包括預(yù)設(shè)信號(hào)處理函數(shù),暫停并等待信號(hào),以及定時(shí)發(fā)出SIGALRM等。
要注意,signal包主要是針對(duì)UNIX平臺(tái)(比如Linux, MAC OS),而Windows內(nèi)核中由于對(duì)信號(hào)機(jī)制的支持不充分,所以在Windows上的Python不能發(fā)揮信號(hào)系統(tǒng)的功能。?
# coding:utf8
import time
import signal
?
?
# 自定義超時(shí)異常
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秒后向進(jìn)程發(fā)送SIGALRM信號(hào)
? ? ? ? ? ? ? ? result = func(*args, **kwargs)
? ? ? ? ? ? ? ? signal.alarm(0) ? ? ? ? ? ? ?# 函數(shù)在規(guī)定時(shí)間執(zhí)行完后關(guān)閉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
基于子線程阻塞實(shí)現(xiàn)超時(shí)
# coding:utf8
import time
import threading
?
?
def callback_func():
? ? print('超時(shí)回調(diào)')
?
?
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) ?# 設(shè)置主線程技術(shù)子線程立刻結(jié)束
? ? ? ? ? ? t.start()
? ? ? ? ? ? t.join(interval) ?# 主線程阻塞等待interval秒
? ? ? ? ? ? if t.is_alive() and callback:
? ? ? ? ? ? ? ? return threading.Timer(0, callback).start() ?# 立即執(zhí)行回調(diào)函數(shù)
? ? ? ? ? ? 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('參數(shù)')
? ? task4('參數(shù)')
輸出:
**********task3****************
0
參數(shù)
1
參數(shù)
超時(shí)回調(diào)
**********task4****************
0
參數(shù)
1
參數(shù)
2
參數(shù)
基于協(xié)程實(shí)現(xiàn)
def callback_func():
? ? print('callback')
?
?
def time_out(interval, callback=None):
? ? def decorator(func):
? ? ? ? def wrapper(*args, **kwargs):
? ? ? ? ? ? ########## 該部分必選在requests之前導(dǎo)入
? ? ? ? ? ? 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
相關(guān)推薦
- 2023-03-01 Maui?Blazor?使用攝像頭實(shí)現(xiàn)代碼_其它綜合
- 2023-02-07 Hive數(shù)據(jù)去重的兩種方式?(distinct和group?by)_數(shù)據(jù)庫(kù)其它
- 2023-01-14 React項(xiàng)目中className運(yùn)用及問(wèn)題解決_React
- 2022-12-23 Kubernetes?權(quán)限管理認(rèn)證鑒權(quán)詳解_云其它
- 2022-12-26 Python常用標(biāo)準(zhǔn)庫(kù)之os模塊功能_python
- 2022-08-20 Android自定義可控制速度的跑馬燈_Android
- 2022-08-05 react+react-beautiful-dnd實(shí)現(xiàn)代辦事項(xiàng)思路詳解_React
- 2022-07-10 初識(shí)form表單中的兩種提交方式
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支