You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程方式访问django-apscheduler的作业属性?

如何在Django视图中访问django-apscheduler的作业历史信息

1. 导入内置模型

django-apscheduler已预先定义好对应数据库模型,直接从包中导入即可:

from django_apscheduler.models import DjangoJob, DjangoJobExecution

2. 查询作业执行历史数据

DjangoJobExecution模型存储了每次作业执行的详细信息(运行时间、时长、状态等),DjangoJob则存储作业的基础配置(名称、关联函数等),两者通过外键关联。根据需求可以灵活查询:

示例1:获取指定作业的最后一次执行记录

假设目标作业的id为spider_crawl_job(可从Django管理后台查看作业的id字段):

# 先定位到目标作业
target_job = DjangoJob.objects.get(id='spider_crawl_job')
# 按运行时间倒序排列,取第一条即为最后一次执行记录
last_exec_record = DjangoJobExecution.objects.filter(job=target_job).order_by('-run_time').first()

# 提取所需属性
if last_exec_record:
    last_run_time = last_exec_record.run_time  # 本地运行时间
    exec_duration = last_exec_record.duration  # 执行时长(单位:秒)
    exec_status = last_exec_record.status  # 执行状态,如'SUCCESS'/'FAILED'

示例2:批量获取所有作业的最新执行记录

如果需要展示所有定时作业的最新运行状态:

from django.db.models import Max

# 按作业分组,获取每个作业的最新执行时间
latest_exec_times = DjangoJobExecution.objects.values('job').annotate(latest_run=Max('run_time'))

# 关联查询完整的执行记录
latest_exec_records = DjangoJobExecution.objects.filter(
    job__in=[item['job'] for item in latest_exec_times],
    run_time__in=[item['latest_run'] for item in latest_exec_times]
).select_related('job')

# 遍历处理每个作业的信息
for record in latest_exec_records:
    job_name = record.job.name
    last_run = record.run_time
    status = record.status

3. 在视图中传递数据到模板

将查询到的信息放入视图上下文,即可在模板中渲染展示:

from django.shortcuts import render

def spider_job_status(request):
    target_job = DjangoJob.objects.get(id='spider_crawl_job')
    last_exec_record = DjangoJobExecution.objects.filter(job=target_job).order_by('-run_time').first()
    
    context = {
        'last_run_time': last_exec_record.run_time if last_exec_record else '从未执行',
        'exec_duration': last_exec_record.duration if last_exec_record else 0,
        'exec_status': last_exec_record.status if last_exec_record else '无执行记录'
    }
    return render(request, 'job_status.html', context)

4. 模板中展示示例

在job_status.html模板中可以这样渲染数据:

<h3>爬虫作业运行状态</h3>
<p>最后运行时间:{{ last_run_time }}</p>
<p>执行时长:{{ exec_duration }} 秒</p>
<p>执行状态:{{ exec_status }}</p>

注意事项

  • 确保已执行django-apscheduler的数据库迁移:python manage.py migrate,否则模型对应的数据库表不会生成。
  • 若作业从未执行过,last_exec_record会返回None,需做空值判断避免报错。

内容的提问来源于stack exchange,提问作者achermaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:20:58