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

标签 python django multithreading python-asyncio periodic-task

你认为在 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.

关于python - 使用 asyncio 在 django 中执行周期性任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43838872/

相关文章:

python - 在Python中,是否有对异常引发者的引用?

Django Graphene,传递 JSON 或 dict 数据作为 Mutation 的输入

python - 基于局部变量的Django条件过滤器

javascript - django-pipeline 不压缩

ios - 我什么时候应该将 Runloop 应用到我的程序中,为什么?

c - 为什么线程不能正常工作?

python - django 填充 html 表单

python - 多输入预训练模型

java - synchronized 关键字给出了预期的输出,但对不同线程调用该方法的顺序不满意

python - 在两个数组的最终轴上按元素相乘