我想在Celery中运行任务,该任务使用线程运行asyncio
事件循环。
tasks.py :
import asyncio
import threading
from celery import Celery
app = Celery('tasks', broker='amqp://guest@rabbitmq//', backend='rpc://guest@rabbitmq//')
sync_proxy_event_loop = asyncio.new_event_loop()
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
sync_proxy_thread = threading.Thread(target=start_loop, args=(sync_proxy_event_loop,), daemon=True)
sync_proxy_thread.start()
@app.task
def check_thread():
return sync_proxy_thread.is_alive()
然后我运行它:
>>> import tasks
>>> r = tasks.check_thread.delay()
>>> r.result
False
它表明线程未运行。我如何解决它:
sync_proxy_thread = None
@app.task
def check_thread():
global sync_proxy_thread
if sync_proxy_thread is None:
sync_proxy_thread = threading.Thread(target=start_loop, args=(sync_proxy_event_loop,), daemon=True)
sync_proxy_thread.start()
return sync_proxy_thread.is_alive()
现在,它表明线程处于活动状态并且正在运行。但是有什么区别呢?我的期望是Celery worker在导入时应在模块中高级执行代码。但这似乎是错误的。实际发生了什么?