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

How to update background task status periodically in Django?

我有一个 Django 项目,其中包含一个很长的 运行 过程。我为此使用了 django-background-tasks 库。它有效,但我想为用户创建一个待定页面并显示任务状态。我应该每 60 秒刷新一次该页面并更新状态。我该怎么做?

谢谢。

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

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

希望对您有所帮助。

希望您了解 Ajax。

如何在 Django 中使用 Ajax:https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

如何每 n 秒 运行 Ajax 编码:https://thisinterestsme.com/ajax-request-every-10-seconds/

如果要部分加载页面,则应将页面分成两部分。其中应包含您要刷新或重新加载的特定 div,将页面名称视为 partial_load.html。而其他页面可以有剩余的代码,将文件名视为full_page.html。 partial_load.html 可以包含在 full_page.html 中,方法是使用 include 标签 ({% include "partial_load.html" %})

 def refresh_page(request):
      if request.is_ajax():
           now = timezone.now()
           pending, running = get_process_status()
           context = {
             "pending": count_pending, 
             "running": count_running
             }
           return render(request, "partial_load.html", context)

full_page.html

 <html>
  <div> Something </div>
   .....
   <div id="status">
    {% include "partial_load.html" %}
   </div>
  ......
  <div> some more stuff </div>
 </html>