forked from shibing624/python-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime_limit.py
More file actions
59 lines (49 loc) · 1.5 KB
/
time_limit.py
File metadata and controls
59 lines (49 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# -*- coding: utf-8 -*-
"""
@author:XuMing([email protected])
@description:
"""
import signal
import time
def set_timeout(num,callback):
def wrap(func):
def handle(signum, frame): # 收到信号 SIGALRM 后的回调函数,第一个参数是信号的数字,第二个参数是the interrupted stack frame.
raise RuntimeError
def to_do(*args,**kwargs):
try:
signal.signal(signal.SIGALRM, handle) # 设置信号和回调函数
signal.alarm(num) # 设置 num 秒的闹钟
print('start alarm signal.')
r = func(*args,**kwargs)
print('close alarm signal.')
signal.alarm(0) # 关闭闹钟
return r
except RuntimeError as e:
callback()
return to_do
return wrap
def after_timeout(): # 超时后的处理函数
print("do something after timeout.")
raise RuntimeError
@set_timeout(2,after_timeout) # 限时 2 秒超时
def connect(): # 要执行的函数
time.sleep(2.4) # 函数执行时间,写大于2的值,可测试超时
return "完成"
class Demo:
@set_timeout(2,after_timeout)
def conn(self):
time.sleep(3)
return "ok"
if __name__ == '__main__':
try:
a = connect()
print(a)
except Exception as e:
a = 'err'
print(a)
b = Demo()
try:
c = b.conn()
print(c)
except RuntimeError as e:
print('run time err.')