Prometheus 无法直接监控 crontab 执行状态,需通过脚本主动输出指标到 textfile 或 Pushgateway 实现可观测性:退出码、成功时间戳、备份大小三类指标写入文件或推送,由 Node Exporter 或 Pushgateway 暴露,Prometheus 抓取后配置差异化告警。

Prometheus 本身不直接监控 crontab 或其他定时任务的执行状态,因为它无法感知脚本是否运行、成功或失败。真正可行的方式是让定时任务“主动暴露状态”,再由 Prometheus 拉取这些结构化指标。关键不在监控 cron 进程,而在监控你调度的业务逻辑是否按预期完成。
改造脚本,输出可采集的状态指标
每个定时脚本执行完毕后,必须留下明确的执行凭证。推荐在脚本末尾写入三类基础指标到文件(如 /var/lib/node_exporter/textfile_collector/backup.prom):
-
退出码:用
$?记录,写为mysql_backup_last_exit_code 0(成功)或1/2(失败) -
最后成功时间戳:用
date +%s写为mysql_backup_last_success_timestamp 1749998400 -
备份文件大小:用
stat -c%s /backup/xxx.sql 2>/dev/null || echo 0写为mysql_backup_last_size_bytes 12567890
确保该文件对 prometheus 用户可读,且每次执行都覆盖更新 —— 这是后续所有监控和告警的数据源头。
用 Node Exporter + textfile 收集器暴露指标
Node Exporter 自带 textfile collector 功能,能自动读取指定目录下的 .prom 文件并暴露为 HTTP 指标:
- 确认 Node Exporter 启动时启用了
--collector.textfile.directory=/var/lib/node_exporter/textfile_collector - 检查
http://localhost:9100/metrics是否包含你写的指标名(如mysql_backup_last_exit_code) - 若无,检查文件权限、路径拼写及 Node Exporter 日志
配置 Prometheus 抓取并定义合理告警
在 prometheus.yml 中添加 job 抓取 Node Exporter 的 metrics 端点:
- 确认
scrape_configs包含指向 Node Exporter 的 job,例如job_name: 'node' - 访问
:9090/targets验证目标状态为 UP - 在 PromQL 中测试:
mysql_backup_last_exit_code是否有值;time() - mysql_backup_last_success_timestamp > 86400是否触发(表示超 24 小时未成功) - 告警规则不要只写“非 0 就告警”,应区分 exit code 含义:比如
exit_code == 2(连接拒绝)设为紧急级,for: 30s;exit_code == 3(权限不足)设为排查级,for: 2m,并附诊断命令注释
短期脚本更适合用 Pushgateway
如果任务运行时间极短(如几秒),而 Prometheus 抓取间隔是 15 秒,很可能错过指标。这时应改用 Pushgateway:
- 脚本执行完,用
curl -X POST --data-binary @metrics.prom http://pushgateway:9091/metrics/job/backup/instance/host1推送 - Prometheus 配置中静态指向 Pushgateway 地址,定期拉取
- 注意 Pushgateway 默认保留数据 2 小时,需配合业务节奏设置
--persistence.file或清理策略
本质上就是让脚本从“黑盒执行”变成“白盒信号”,Prometheus 才能真正看清它干了什么、干得怎么样。


















