shell脚本放到crontab里定时执行

需求需要定时检查zookeeper进程和mq进程,当进程不存在时去需要自动启动,把检查进程的脚本写好后,添加到crontab中 设置定时多久执行。


检测zookeeper进程脚本 check_zk.sh

#!/bin/sh
#echo `date`
source /etc/profile
PID=`ps aux | grep QuorumPeerMain | grep -v "grep" |wc -l`
#pid=`ps aux | grep QuorumPeerMain | grep -v "grep"`
echo $PID
while [ $PID -eq 0 ]; do
    echo `date`
    echo '开始启动zk脚本'
    /home/ekanet/esb/zookeeper-3.4.6/bin/zkServer.sh start & 
   sleep 1
    exit 0
done


检测mq进程脚本 check_mq.sh

#!/bin/sh
#echo `date`
source /etc/profile
PID=`ps aux | grep activemq.jar | grep -v "grep" |wc -l`
#pid=`ps aux | grep activemq.jar | grep -v "grep"`
echo $PID
while [ $PID -eq 0 ]; do
     echo `date`
     echo '开始启动mq脚本'
    /home/ekanet/esb/apache-activemq-5.13.4/bin/activemq  start &
   sleep 1
    exit 0
done




编辑crontab 使用命令 crontab -e


#每隔1分钟检测一次
*/1 * * * * /home/ekanet/esb/scripts/check_zk.sh >> /home/ekanet/esb/scripts/zklog.log
*/1 * * * * /home/ekanet/esb/scripts/check_mq.sh >> /home/ekanet/esb/scripts/mqlog.log

在实际使用中碰到直接执行脚本check_zk.sh能运行,但是放置到crontab中执行时并不能把zk服务启动起来。解决方法

有些shell脚本正常执行没问题,但放到crontab里就执行不成功,原因是因为crontab执行脚本的时候不会读取用户的环境变量等配置
解决方法
1.在shell前面export下$PATH

 
 
  • 1
export $PATH

2.或者source下/etc/profile

source /etc/profile

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...