django上的asyncio RuntimeError:任务<task pending =“”coro =“&lt; future_timer()”running =“”got =“”future =“”<future =“”pending =“”>附加到不同的循环

时间:2017-05-26 13:35:29

标签: python django python-asyncio

在django上使用命令行运行asyncio的任务。我已经设置芹菜和芹菜调用函数来创建asyncio循环,它正在调用函数,它等待asyncio,但它给出了以下错误。

  

yield self#这告诉Task等待完成。   RuntimeError:任务&gt;让Future附加到一个不同的循环。

我在wsgi上使用python3运行django,在守护进程上运行celery。以下是代码示例。

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()

我在这里呼吁跟随不同功能的部分如下。

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 个答案:

没有答案