Skip to content

Commit

Permalink
default aloop used for background tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
divi255 committed Aug 22, 2019
1 parent 6ff8b91 commit bc4ed20
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
7 changes: 5 additions & 2 deletions atasker/supervisor.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,12 @@ def create_aloop(self, name, daemon=False, start=True, default=False):
def set_default_aloop(self, aloop):
self.default_aloop = aloop

def get_aloop(self, name):
def get_aloop(self, name=None, default=True):
with self._lock:
return self.aloops.get(name)
if name is not None:
return self.aloops.get(name)
elif default:
return self.default_aloop

def start_aloop(self, name):
with self._lock:
Expand Down
7 changes: 5 additions & 2 deletions atasker/threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,11 @@ def background_task(f, *args, **kwargs):
tt: TT_THREAD (default) or TT_MP (TT_COROUTINE is detected
automatically)
callback: callback function for TT_MP
loop: asyncio loop or aloop object
loop: asyncio loop or aloop object (optional)
Raises:
RuntimeError if coroutine function is used but loop is not specified
RuntimeError: if coroutine function is used but loop is not specified
and supervisor doesn't have default aloop
"""

def gen_mp_callback(task_id, callback, supervisor):
Expand All @@ -157,6 +158,8 @@ def start_task(*args, **kw):
supervisor = kwargs.get('supervisor', task_supervisor)
if tt == TT_COROUTINE or asyncio.iscoroutinefunction(f):
loop = kwargs.get('loop')
if isinstance(loop, str) or loop is None:
loop = supervisor.get_aloop(loop)
if not loop:
raise RuntimeError('loop not specified')
if isinstance(loop, ALoop):
Expand Down
2 changes: 1 addition & 1 deletion tests/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ async def t2(x):
return x * 2

a = task_supervisor.create_aloop('test2')
background_task(t1, loop=a)()
background_task(t1, loop='test2')()
wait()
self.assertEqual(result.test_aloop_background_task, 1)
self.assertEqual(a.run(t2(2)), 4)
Expand Down

0 comments on commit bc4ed20

Please sign in to comment.