10

I found that most of the docs regarding Django Channels are about WebSockets. But I want to use them in a different way, and I believe it is possible.

How to run the async periodic task using Django channels? For example, I want to check the temperature on some website (through the API) every 15 seconds and I need a notification when its hit > 20.

It also means that this task will live for a long time (maybe even for 3 month), is Django capable of keeping the consumers live for a long time?

Thank you.

4

1 回答 1

6

Channels 很容易用于后台任务 - 有关使用新版本 Channels 执行此操作的说明,请参见此处:

https://github.com/jayhale/channels-examples-bg-task

有了后台任务,您可以设置一个可以使用 cron 调用的任务,该任务可以在您想要的任何时间将您的任务放入队列中。cron 的缺点是它没有开箱即用的亚分钟调度 - 需要一些黑客攻击。请参阅:每 30 秒运行一次 cron

例如:

将作业添加到应用用户的 crontab:

# crontab
/5 * * * * python manage.py cron_every_5_minutes

您的自定义管理命令可以生成频道任务:

# myapp/management/commands/cron_every_5_minutes.py

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    channel_layer = get_channel_layer()
    help = 'Periodic task to be run every 5 minutes'

    def handle(self, *args, **options):
        async_to_sync(channel_layer.send)('background-tasks', {'type': 'task_5_min'})

关于工人的预期可靠性 - 他们可以无限期地运行,但你应该期望他们偶尔会失败。管理工作人员更多的是关于您打算如何监督流程(或容器,或者您正在构建的架构)的问题。

于 2018-06-06T18:21:36.440 回答