Skip to content

[WIP]implement accurate timeout function #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions slack_bot/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# coding=utf-8
import time
import os
import re

from flask import Flask
from flask import Flask, g

from flask_slackbot import SlackBot

Expand Down Expand Up @@ -37,10 +38,14 @@ def create_app(config=None):
slackbot.set_handler(callback)
slackbot.filter_outgoing(_filter)

@app.before_request
def start_time_it():
g.time = time.time()

return app


@timeout(30.0)
@timeout(g, 30.0)
def callback(kwargs):
s = convert2str(kwargs['text'])
trigger_word = convert2str(kwargs['trigger_word'])
Expand Down
9 changes: 5 additions & 4 deletions slack_bot/plugins/github_issue.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ def handle(data):


if __name__ == '__main__':
from flask import Flask
app = Flask(__name__)
app.config['org_name'] = 'python-cn'
print handle(None)
# from flask import Flask
# app = Flask(__name__)
# app.config['org_name'] = 'python-cn'
# print handle(None)
pass
12 changes: 9 additions & 3 deletions slack_bot/utils.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from multiprocessing import TimeoutError
from multiprocessing.pool import ThreadPool
from functools import wraps


def timeout(seconds):
def timeout(g, seconds, default="timeout"):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
pool = ThreadPool(processes=1)
async_result = pool.apply_async(fn, args=args, kwds=kwargs)
try:
return async_result.get(seconds)
# the time cost before start fn
cost_time = time.time() - g.time
return async_result.get(seconds - cost_time)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里好精确... 👍

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dongweiming 暂时遇到了上下文的问题,解决中

except TimeoutError:
return kwargs.pop('default', {'text': 'timeout'})
return default() if callable(default) else default
finally:
pool.close()
pool.terminate()
return wrapper
return decorator