-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.py
35 lines (26 loc) · 856 Bytes
/
tasks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from time import sleep
from celery import Celery, shared_task
from asyncio import sleep
from asgiref.sync import async_to_sync
import asyncio
app = Celery("tasks", backend="rpc://", broker="pyamqp://guest@localhost//")
@app.task
def reverse_string(my_string: str):
return my_string[::-1]
@app.task(bind=True)
def add(self, x, y):
# Your actual async function
async def async_add(x, y):
return x + y
loop = asyncio.get_event_loop()
# If there's no running loop, we will create a new one and close it after the task
if loop.is_closed():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(async_add(x, y))
finally:
loop.close()
else:
result = loop.run_until_complete(async_add(x, y))
return result