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

通过Rundeck API获取未来X小时内待运行作业名称和ID的脚本修改方案(Azure DevOps Pipeline执行异常)

通过Rundeck API获取未来X小时内待运行作业名称和ID的脚本修改方案(Azure DevOps Pipeline执行异常)

嗨,我看了你的问题和代码,核心问题应该是时区不匹配导致的!你说所有作业时区都是UTC,但你的脚本里用datetime.now()获取的是运行脚本的Agent本地时区时间,而Rundeck返回的nextRunAt是带UTC时区标记的时间,两者直接比较就会出现偏差,所以那些每2小时40分钟运行的作业没被正确识别出来。

咱们来改两个关键地方就能解决:

1. 统一时区为UTC

把当前时间转换为UTC时区的时间,确保和Rundeck返回的时间时区一致。

替换原来的:

current_time = datetime.now()

改为:

current_time = datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

2. 加入作业ID的收集

你想要显示作业ID,所以在收集作业信息的时候把job['id']也加进去。

原来的:

upcoming_jobs.append((job['name'], next_run_at))

改为:

upcoming_jobs.append((job['name'], job['id'], next_run_at))

同时对应的打印部分也要调整:

print("Job Name: {}, Job ID: {}, Next Scheduled: {}".format(job_name, job_id, next_run_at))

修改后的完整脚本

import requests
from datetime import datetime, timedelta

api_token = '$(api_token)$' 
project_name = '$(project_name)$'

api_url = "https://infosys:4443/api/19/project/{}/jobs".format(project_name)

headers = {
    "Accept": "application/json",
    "X-Rundeck-Auth-Token": api_token,
    "Content-Type": "application/json"
}

response = requests.get(api_url, headers=headers, verify=False)

if response.status_code == 200:
    scheduled_jobs = response.json()
    # 修改:使用UTC时区的当前时间
    current_time = datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
    three_hours_from_now = current_time + timedelta(hours=3)
    upcoming_jobs = []
    for job in scheduled_jobs:
        if 'schedule' in job and 'nextRunAt' in job['schedule']:
            next_run_at = datetime.strptime(job['schedule']['nextRunAt'], "%Y-%m-%dT%H:%M:%S%z")
            if current_time <= next_run_at <= three_hours_from_now:
                # 修改:加入作业ID
                upcoming_jobs.append((job['name'], job['id'], next_run_at))
    if upcoming_jobs:
        print("Upcoming jobs in the next 3 hours:")
        # 修改:打印作业ID
        for job_name, job_id, next_run_at in upcoming_jobs:
            print("Job Name: {}, Job ID: {}, Next Scheduled: {}".format(job_name, job_id, next_run_at))
    else:
        print("No jobs scheduled in the next 3 hours.")
else:
    print("Error fetching scheduled jobs:", response.text)

额外检查点

  • 确认Rundeck API返回的nextRunAt格式确实是%Y-%m-%dT%H:%M:%S%z(比如2024-05-20T14:30:00+0000),如果格式有变化,需要调整strptime的格式字符串。
  • 可以在脚本里打印一下current_time和next_run_at的具体值,看看时区是否一致,方便排查问题。

这样修改后,你的脚本就能正确识别UTC时区下未来3小时内的作业,包括那些每2小时40分钟运行的周期性作业了。

备注:内容来源于stack exchange,提问作者eddie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 11:49:34