Thanks for the fast answer @ahopkins
First Approach
I tried doing this:
@app.main_process_start
async def my_task(app, loop):
print(f"MY TASK - PID: {os.getpid()}")
await asyncio.sleep(2)
app.add_task(my_task(app, loop))
But it runs twice and then nothing happens.
When I kill the process I got this:
Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<my_task() done, defined at /path/to/file/asgi.py:28> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f9bd5fbe760>()]>>
I tried also doing this:
async def my_task(app):
print(f"MY TASK - PID: {os.getpid()}")
await asyncio.sleep(2)
app.add_task(my_task(app))
@app.main_process_start
async def my_outer_task(app, loop):
app.add_task(my_task(app))
And what I got is that it runs once and I get the same message when killing the process.
What I need is that my_task
runs every 2 seconds “forever”.
Second Approach
Another approach that I tried was to select only 1 worker to run the background task by assigning the pid
into app.ctx.pid
. In the first run the worker1 will set app.ctx.pid
with its pid
. A the second run check if the pid
of the worker is the same as set, if it does then execute normally. If another worker runs it (with a different pid
) just do nothing and return. I tried this but It did not worked: the app.ctx.pid
changed constantly. I checked if there were different instances of app
in each worker and no, it was the same instance.
It’s something like this:
async def task(app):
await asyncio.sleep(2)
print(f"TASK - PID: {os.getpid()}")
if not hasattr(app.ctx, "pid"):
app.ctx.pid = os.getpid()
elif app.ctx.pid != os.getpid():
return
else:
pass
app.add_task(task)