解决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 定时任务执行失败问题的详细内容的总结,更多请关注码云笔记其它相关文章!
以上关于解决Linux crontab定时任务执行失败问题的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » 解决Linux crontab定时任务执行失败问题

微信
支付宝