using asyncio to do periodic task in django

情到浓时终转凉″ 提交于 2019-12-01 10:03:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!