当前位置: 代码网 > 服务器>服务器>Linux > Linux crontab定时任务执行失败处理方案

Linux crontab定时任务执行失败处理方案

2024年07月03日 Linux 我要评论
背景写了个postman脚本,准备放在服务器每隔5分钟执行一次,postman命令在/usr/local/bin/postman目录现象cron脚本1.crontab系统配置[root@node2 ~

背景

写了个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 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)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com