从Django后台任务获取任务状态

时间:2017-10-16 09:24:35

标签: django

我正在使用Django,我想开始一些后台任务。我找到了库“Django后台任务”。它几乎拥有我需要的一切但我无法找到如何在文档(http://django-background-tasks.readthedocs.io/en/latest/)中的任何位置获取任务的状态(待定/运行/完成)。如果有人能告诉我如何获得任务的状态,那将对我非常有帮助。

1 个答案:

答案 0 :(得分:2)

任务将插入到数据库表background_task中,完成后,任务将从background_task表移至background_task_completedtask表。您可以使用此信息创建视图以获取所有/特定任务的状态。

示例

from background_task.models import Task
from background_task.models_completed import CompletedTask
from datetime import datetime
from django.utils import timezone

def get_status(request):
    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.
    pending_tasks_qs = Task.objects.filter(run_at__gt=now)
    running_tasks_qs = 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.
    completed_tasks_qs = CompletedTask.objects.all()

    # main logic here to return this as a response.

    # just for test
    print (pending_tasks_qs, running_tasks_qs, completed_tasks_qs)
    return HttpResponse("ok")

最后,在urlpatterns中注册此视图并检查状态。