gpt4 book ai didi

python - 如何从 django 前端定时安排任务?

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:13 24 4
gpt4 key购买 nike

我正在使用 Django 编写灌溉系统,并使用 Celery 来处理异步任务。

在我的应用程序中,用户选择他想要激活灌溉的日期和时间,这存储在数据库中,他可以随时更新它们。

我知道我可以安排这样的任务,但我想更新时间。

from celery.task.schedules import crontab
from celery.decorators import periodic_task

@periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
print("This runs every Monday morning at 7:30a.m.")

另一种方法是使用 python-crontab

最佳答案

通过创建一个运行时表来完成类似的操作,该表列出了我想要运行的内容以及何时可以从 Django 选择。

定期任务本身被安排为每 30 秒运行一次,并检查此表中是否有任何请求准备好执行并调用其中一个工作人员。

编辑:根据格雷厄姆的要求,举一个例子

Django 中用于设置节拍的设置:

CELERY_BEAT_SCHEDULE = {
'Runtime': {
'task': 'Runtime',
'schedule': timedelta(seconds=15),
},
}

调用 Django 中定义的模型(例如,irrigation_requests)的任务,用户将通过前端更新该模型:

def Runtime():
#get all from model in state requested
irrigation_job=Irrigation_Requests.objects.filter(Status__in=['Requested'])

# Process each requested if flag to do just one thing then you could just test irrigation_job exists
for job in irrigation_job:
....
print ("This runs every when requested and depending on job parameters stored in your model can have further scope")

#update requested this could be done in loop above
irrigation_job.update(Status='Processed')

关于python - 如何从 django 前端定时安排任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com