Skip to content

Commit 368b407

Browse files
committed
implement accurate timeout function
1 parent db6f999 commit 368b407

File tree

3 files changed

+20
-9
lines changed

3 files changed

+20
-9
lines changed

slack_bot/app.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
# coding=utf-8
2+
import time
23
import os
34
import re
45

5-
from flask import Flask
6+
from flask import Flask, g
67

78
from flask_slackbot import SlackBot
89

@@ -37,10 +38,14 @@ def create_app(config=None):
3738
slackbot.set_handler(callback)
3839
slackbot.filter_outgoing(_filter)
3940

41+
@app.before_request
42+
def start_time_it():
43+
g.time = time.time()
44+
4045
return app
4146

4247

43-
@timeout(30.0)
48+
@timeout(g, 30.0)
4449
def callback(kwargs):
4550
s = convert2str(kwargs['text'])
4651
trigger_word = convert2str(kwargs['trigger_word'])

slack_bot/plugins/github_issue.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ def handle(data):
3737

3838

3939
if __name__ == '__main__':
40-
from flask import Flask
41-
app = Flask(__name__)
42-
app.config['org_name'] = 'python-cn'
43-
print handle(None)
40+
# from flask import Flask
41+
# app = Flask(__name__)
42+
# app.config['org_name'] = 'python-cn'
43+
# print handle(None)
44+
pass

slack_bot/utils.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,24 @@
11
#!/usr/bin/env python
22
# -*- coding: utf-8 -*-
3+
import time
34
from multiprocessing import TimeoutError
45
from multiprocessing.pool import ThreadPool
56
from functools import wraps
67

78

8-
def timeout(seconds):
9+
def timeout(g, seconds, default="timeout"):
910
def decorator(fn):
1011
@wraps(fn)
1112
def wrapper(*args, **kwargs):
1213
pool = ThreadPool(processes=1)
1314
async_result = pool.apply_async(fn, args=args, kwds=kwargs)
1415
try:
15-
return async_result.get(seconds)
16+
# the time cost before start fn
17+
cost_time = time.time() - g.time
18+
return async_result.get(seconds - cost_time)
1619
except TimeoutError:
17-
return kwargs.pop('default', {'text': 'timeout'})
20+
return default() if callable(default) else default
21+
finally:
22+
pool.close()
1823
return wrapper
1924
return decorator

0 commit comments

Comments
 (0)