Django +后台任务如何初始化 [英] Django + background-tasks how to initialize
问题描述
我有一个基本的django项目,可用作(Condor)计算集群的前端接口,以生成模拟.用户可以从django应用程序开始模拟(在Condor中).与仿真相关的元数据和仿真状态保存在数据库中.
I have a basic django projects that I use as a front end interface for a (Condor) computing cluster for generating simulations. From the django app the users can start simulations (in Condor). The simulation related meta-data and the simulation state are kept in a DB.
我需要添加一个新功能:(部分)模拟完成时通知.
I need to add a new feature: notification when (some) simulations are done.
因为我想要一个简单的解决方案(并且我已经在使用后台任务),所以我一直在考虑使用重复任务,该任务以固定的时间间隔向Condor查询任务,更新数据库,并在必要时发送通知.
Since I want a simple solution (and I already using background tasks) I was thinking to use repeating task that at fixed intervals query Condor about the tasks, updates the DB and if necessary sends notifications.
因此,如果我想每10分钟更新一次该状态,我将得到以下信息:
So if I want to update every 10 min that statuses I will have something like:
@background(schedule=1)
def check_simulations(repeat=600):
# lookup simulation statuses
simulation_list = get_Simulations()
for sim in simulations_list:
if sim.status == Simulation.DONE:
user.email_user('Simulation Complete', 'You have been notified')
def initialize():
check_simulations()
然而,必须启动(调用一次)此任务(或更佳地说,initialize()方法)以创建和计划check_simulations()任务(该任务实际上将对调用进行序列化并将其保存在DB中);之后,后台任务线程将读取并执行并重新计划它(如果有错误)
However this task (or better say the initialize() method) must be started (called once) to create and schedule the check_simulations() task (which will practically serialize the call and save it in the DB); after that the background-tasks thread will read it and execute and also reschedule it (if there is error)
我的问题:
- 我应该在哪里将对initialize()方法的调用仅运行一次?
例如urls.py这样的地方,但这是一个非常丑陋的解决方案.有更好的方法吗?
One such place could be for instance the urls.py but this is an extremely ugly solution. Is there a better way ?
- 如何确保服务器重启不会创建和安排新任务(如果已经存在)如果已经安排了任务(因此序列化的任务在background-tasks表中)并且重新启动了Web服务器,因此再次调用了initialize()方法,以便创建并安排了新任务,则可能会发生这种情况.
推荐答案
我遇到了类似的问题,并且我通过这种方式解决了该问题.
i had a similar problem and i solved it this way.
我在urls.py中初始化了我的任务,我不知道您是否可以使用其他地方来放置它,还要添加它,以及是否要检查该任务是否已经在数据库中
i initialize my task in urls.py, i dont know if you can use other places to put it ,also added and if, to check if the task its allready in the database
from background_task.models import Task
if not Task.objects.filter(verbose_name="update_orders").exists():
tasks.update_orders(repeat=300, verbose_name="update_orders")
我已经对其进行了测试,并且效果很好,您还可以使用其他参数(例如name,hash,...)搜索订单.
i have tested it and it works fine, you can also search for the order with other parameters like name, hash ,...
您可以在此处检查任务模型: https://github.com/arteria/django-background-tasks/blob/master/background_task/models.py
you can check the task model here: https://github.com/arteria/django-background-tasks/blob/master/background_task/models.py
这篇关于Django +后台任务如何初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!