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
  1. /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 25 17:25:01 node2 crond[75796]: sendmail: fatal: parameter inet_interfaces: no local interface found for ::1

服务正常

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

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

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

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

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

添加定时任务

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

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

Sun Jun 25 17:52:01 CST 2023

检查定时任务环境

因为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不对。。。。

Sun Jun 25 17:34:01 CST 2023
/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
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值