问题
Do you think it is possible to use asyncio to run a task every n seconds in django, so that the main process wouldn't be blocked?
Something for example that would print every 5 min in console, like:
import asyncio
from random import randint
async def do_stuff(something, howmany):
for i in range(howmany):
print('We are doing {}'.format(something))
await asyncio.sleep(randint(0, 5))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
work = [
asyncio.ensure_future(do_stuff('something', 5)),
]
loop.run_until_complete(asyncio.gather(*work))
It seems that django will stop working while the loop is running. Even if this can be made to work in development, how would it behave when the site goes live on something like apache or gunicorn?
回答1:
While it would be possible to achieve this with a lot of hard work. Much simpler is to use the time honoured practice of using a cron job. See this: Using django for CLI tool
Nowadays a more popular approach (among django devs at any rate) is to use celery. Specifically celery beat
celery beat is a scheduler; It kicks off tasks at regular intervals, that are then executed by available worker nodes in the cluster.
来源:https://stackoverflow.com/questions/43838872/using-asyncio-to-do-periodic-task-in-django