2017-05-08 98 views
1

您认为可以使用asyncio在django中每n秒运行一次任务,以便主进程不会被阻塞?使用asyncio在django中执行周期性任务

的东西,例如,将打印每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之类的网站上运行时它的行为如何?

+0

也许使用多处理将是一种替代? – Mikael

回答

4

尽管可以通过很多努力来实现这一目标。更简单的是使用使用cron作业的优秀实践。看到这个:Using django for CLI tool

时下更流行的方法(在任何速率的django开发者之间)是使用芹菜。具体celery beat

芹菜拍是一个调度程序;它定期启动任务, 然后由集群中的可用工作节点执行。