Skip to main content
 首页 » 编程设计

python之使用 asyncio 在 django 中执行周期性任务

2025年05月04日30youxin

你认为在 django 中可以使用 asyncio 每 n 秒运行一次任务,这样主进程就不会被阻塞吗?

例如,控制台每 5 分钟打印一次,例如:

    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)) 

似乎django 会在循环运行时停止工作。即使这可以在开发中发挥作用,当网站在 apache 或 gunicorn 等平台上运行时它会如何表现?

请您参考如下方法:

虽然通过大量的努力工作是有可能实现这一目标的。更简单的方法是使用历史悠久的 cron 作业。看到这个:Using django for CLI tool

如今,一种更流行的方法(至少在 django 开发人员中)是使用 celery。具体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.