asyncio on django RuntimeError: Task <Task pending coro=<future_timer() running got Future <Future pending> attached to a different loop

Viewed 1255

Task on asyncio running with command line on django. I have setup celery and celery is calling function to create loop on asyncio and it is calling to function which is having await of asyncio but it gives following error.

yield self # This tells Task to wait for completion. RuntimeError: Task > got Future attached to a different loop.

I am running django with python3 on wsgi and celery on daemon process. Following is code example.

import asyncio
import datetime


@asyncio.coroutine
def slow_operation(name, sec):
    message = '%s started at %s' % (name, datetime.datetime.now())
    print(message)
    yield from asyncio.sleep(sec)
    return '%s ended at %s after %s seconds' % (name, datetime.datetime.now(), sec)


def got_result(future):
    print(future.result())


def run_process(name, sec):
    task = loop.create_task(slow_operation(name, sec))
    task.add_done_callback(got_result)

loop = asyncio.get_event_loop()

i = [{'name': 'First Process', 'sec': 7},
     {'name': 'Second Process', 'sec': 3},
     {'name': 'Third Process', 'sec': 10},
     {'name': 'Fourth Process', 'sec': 2},
     {'name': 'Fifth Process', 'sec': 2}]

for val in i:
    run_process(val['name'], val['sec'])

loop.run_forever()

Here i am calling following part from different function as follow.

def create_asyncio_future_tasks():

    loop = asyncio.get_event_loop()

    i = [{'name': 'First Process', 'sec': 7},
         {'name': 'Second Process', 'sec': 3},
         {'name': 'Third Process', 'sec': 10},
         {'name': 'Fourth Process', 'sec': 2},
         {'name': 'Fifth Process', 'sec': 2}]

    for val in i:
        run_process(val['name'], val['sec'])

    loop.run_forever()
0 Answers
Related