如何在Django中定期更新后台任务状态?

问题描述 投票:0回答:1

我有一个django项目,其中包含一个运行时间较长的过程。我已经为此使用django-background-tasks库。它可以工作,但是我想为用户创建一个待处理页面并显示任务状态。我应该每60秒刷新一次该页面并更新状态。我该怎么办?

谢谢。

python django background-process background-task long-running-processes
1个回答
0
投票

如果您迁移了数据库,则在安装background_task软件包后进行更改(然后只有数据库具有background_task软件包的表)。您可以通过简单地查询background_task模型来获取在后台运行的进程的状态,例如查询其他用户定义的模型。

from background_task.models import Task, CompletedTask
from django.utils import timezone

def get_process_status(parameters):
     now = timezone.now()
     # pending tasks will have `run_at` column greater than current time.
     # Similar for running tasks, it shall be
     # greater than or equal to `locked_at` column.
     # Running tasks won't work with SQLite DB,
     # because of concurrency issues in SQLite.
     # If your task still not started running and waiting in the queue, then you  can find it in pending_tasks

     pending_tasks = Task.objects.filter(run_at__gt=now)

     # If your your task is in running state, you can find it in running_tasks

     running_tasks = Task.objects.filter(locked_at__gte=now)

     # Completed tasks goes in `CompletedTask` model.
     # I have picked all, you can choose to filter based on what you want.
     # If your task completed you can find it in Completed task model.

     completed_tasks = CompletedTask.objects.all()

     # If you want the result in json format just add .values() at the end of the
     # ORM query like "completed_tasks = CompletedTask.objects.all().values()"     
     print(completed_tasks, running_tasks, pending_tasks)
     ......
     ......
     return process_status

如果要每60秒运行一次功能,请使用background_task安排任务。示例代码:

@background(schedule=60)
def get_process_status(parameters):
  .....
  code
  .....
  return process_status

希望它会帮助您。

© www.soinside.com 2019 - 2024. All rights reserved.