Skip to content

Commit

Permalink
Run event loop in new thread
Browse files Browse the repository at this point in the history
  • Loading branch information
aluminiumgeek committed Mar 21, 2016
1 parent 65bb1ae commit e0bc4d8
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions telegram.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import imp
import logging
import json
from threading import Thread

import requests
from requests.exceptions import ConnectionError, ReadTimeout
Expand All @@ -32,24 +33,28 @@ class Executor(object):

def __init__(self, callback):
self.callback = callback
self.loop = asyncio.get_event_loop()

# Run new event loop in another thread
Thread(target=self.init_loop).start()

def __del__(self):
self.close()

def init_loop(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.loop.run_forever()

def call(self, module, *args, **kwargs):
chat_id = kwargs.pop('chat_id')
task = asyncio.ensure_future(self.run(module, *args, **kwargs))
task = asyncio.run_coroutine_threadsafe(self.run(module, *args, **kwargs), self.loop)
task.add_done_callback(functools.partial(self.callback, chat_id=chat_id))
return task

def wait(self, tasks):
if tasks:
self.loop.run_until_complete(asyncio.wait(tasks))

@asyncio.coroutine
def run(self, module, *args, **kwargs):
return module(*args, **kwargs)
future = self.loop.run_in_executor(None, functools.partial(module, *args, **kwargs))
yield from future

def close(self):
self.loop.close()
Expand Down Expand Up @@ -178,7 +183,7 @@ def start(self):
tasks.append(process)
elif isinstance(process, (list, tuple)):
tasks += list(process)
self.executor.wait(tasks)
logging.debug('Running tasks: {}'.format(tasks))

def process(self, update):
"""
Expand Down

0 comments on commit e0bc4d8

Please sign in to comment.