Skip to content

Commit 414addc

Browse files
committed
implement accurate timeout function
1 parent db6f999 commit 414addc

File tree

3 files changed

+30
-9
lines changed

3 files changed

+30
-9
lines changed

slack_bot/app.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
# coding=utf-8
2+
import time
23
import os
34
import re
5+
from multiprocessing.pool import ThreadPool
46

5-
from flask import Flask
7+
from flask import Flask, g
68

79
from flask_slackbot import SlackBot
810

@@ -37,10 +39,23 @@ def create_app(config=None):
3739
slackbot.set_handler(callback)
3840
slackbot.filter_outgoing(_filter)
3941

42+
def _set_time():
43+
while True:
44+
g.time = time.time()
45+
46+
@app.before_request
47+
def start_time_it():
48+
g.pool = ThreadPool(processes=1)
49+
g.pool.apply_async(_set_time)
50+
51+
@app.after_request
52+
def end_time_it():
53+
g.pool.close()
54+
4055
return app
4156

4257

43-
@timeout(30.0)
58+
@timeout(g, 30.0)
4459
def callback(kwargs):
4560
s = convert2str(kwargs['text'])
4661
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)