解决Linux crontab定时任务执行失败问题

目录
文章目录隐藏
  1. 现象
  2. 分析过程
  3. 修改方案

解决 Linux crontab 定时任务执行失败问题

技术笔记主要介绍了 Linux crontab 定时任务执行失败处理方案,具有很好的参考价值。特意写了个 postman 脚本,准备放在服务器每隔 5 分钟执行一次,postman 命令在/usr/local/bin/postman 目录。

现象

cron 脚本

1. crontab 系统配置

[root@node2 ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

2. crontab 定时任务

*/5 * * * * /mnt/script/postman/b.sh

3. /mnt/script/postman/b.sh

#!/bin/sh
postman collection run /mnt/script/postman/blade-1.json >> /tmp/cron_test.log

执行结果

/tmp/cron_test.log 中没有执行记录,脚本中的接口也没触发

分析过程

检查 cront 服务是否正常运行

service crond status
Redirecting to /bin/systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2023-06-25 17:01:35 CST; 44min ago
 Main PID: 75796 (crond)
    Tasks: 1
   Memory: 664.0K
   CGroup: /system.slice/crond.service
           └─75796 /usr/sbin/crond -n

Jun 18 17:25:01 node2 crond[75796]: sendmail: fatal: parameter inet_interfaces: no local interface found for ::1

服务正常

检查定时任务是否正常触发

查看定时任务日志tail -100f /var/log/cron

Jun 18 17:49:01 node2 CROND[90291]: (root) CMD (/mnt/script/postman/b.sh)

可以看到任务已经被触发了。

检查触发的任务是否正常运行

添加定时任务

* * * * * date >> /tmp/cron_test.log

在/tmp/cron_test.log 中有出现执行结果,说明定时任务可以正常触发和执行。

Tues Jun 18 17:52:01 CST 2024

检查定时任务环境

因为 postman 是单独安装的,cli 在/usr/local/bin 目录下,想看一下 cron 执行的时候环境变量是什么。

修改/mnt/script/postman/b.sh

echo $PATH >> /tmp/cron_test.log
postman collection run /mnt/script/postman/blade-1.json >> /tmp/cron_test.log

cron 执行后发现/tmp/cron_test.log 中的 PATH 不对。

Tues Jun 18 17:34:01 CST 2024
/usr/bin:/bin

至此问题原因找到了,是因为 cron 执行环境中没有 postman 命令,只要触发一下环境配置或者指定 postman 的路径即可。

修改方案

方案一 :添加环境变量

修改/mnt/script/postman/b.sh 脚本

#!/bin/sh

. /etc/profile #环境变量生效 前提是你的命令所在环境有在这个文件中配置
echo $PATH >> /tmp/cron_test.log
postman collection run /mnt/script/postman/blade-1.json >> /tmp/cron_test.log

方案二:直接指定命令目录

修改/mnt/script/postman/b.sh 脚本

#!/bin/sh
/usr/local/bin/postman collection run /mnt/dengwei/postman/blade-1.json >> /tmp/cron_test.log

以上就是本技术笔记关于解决 Linux crontab 定时任务执行失败问题的详细内容的总结,更多请关注码云笔记其它相关文章!

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系maynote@foxmail.com处理
码云笔记 » 解决Linux crontab定时任务执行失败问题

发表回复