Skip to main content
 首页 » 编程设计

python之任务管理守护进程

2025年05月04日7虾米姐

我必须用我的 django ORM 数据做一些长时间(我想是 2-3 天)的任务。我环顾四周,没有找到任何好的解决方案。

django-tasks - http://code.google.com/p/django-tasks/没有很好的记录,我不知道如何使用它。

celery - http://ask.github.com/celery/对我的任务来说太过分了。 它适合长时间的任务吗?

所以,我需要做的是从我的数据库中获取所有数据或部分数据,例如:

Entry.objects.all() 

然后我需要为每个 QuerySet 执行相同的函数。

我认为它应该在 2-3 天左右有效。

那么,也许有人会为我解释如何构建它。

P.S:目前我只有一个想法,使用cron和数据库来存储流程执行时间线。

请您参考如下方法:

使用 Celery 子任务。这将允许您启动一个长时间运行的任务(它下面有许多短期运行的子任务),并在 Celery 的任务结果存储中保留有关其执行状态的良好数据。作为一个额外的好处,子任务将分布在工作进程中,使您可以充分利用多核服务器甚至多台服务器来 reduce task 运行时间。

编辑:示例:

import time, logging as log 
from celery.task import task 
from celery.task.sets import TaskSet 
from app import Entry 
 
@task(send_error_emails=True) 
def long_running_analysis(): 
    entries = list(Entry.objects.all().values('id')) 
    num_entries = len(entries) 
    taskset = TaskSet(analyse_entry.subtask(entry.id) for entry in entries) 
    results = taskset.apply_async() 
    while not results.ready() 
        time.sleep(10000) 
        print log.info("long_running_analysis is %d% complete", 
                       completed_count()*100/num_entries) 
    if results.failed(): 
        log.error("Analysis Failed!") 
    result_set = results.join() # brings back results in  
                                # the order of entries 
    #perform collating or count or percentage calculations here 
    log.error("Analysis Complete!") 
 
@task 
def analyse_entry(id): # inputs must be serialisable 
    logger = analyse_entry.get_logger() 
    entry = Entry.objects.get(id=id) 
    try: 
        analysis = entry.analyse() 
        logger.info("'%s' found to be %s.", entry, analysis['status']) 
        return analysis # must be a dict or serialisable. 
    except Exception as e: 
        logger.error("Could not process '%s': %s", entry, e) 
        return None  

如果您的计算无法分离到每个条目的任务,您始终可以将其设置为一个子任务执行理货,一个子任务执行另一种分析类型。这仍然有效,并且仍然可以让您从平行主义中受益。