Linux下使用shell脚本+定时任务crontab实现定时重启Jar包

最近项目上有个小需求,在Linux下定时重启SpringBoot项目打好的Jar包,定时任务使用crontable。

crontable -e 添加定时任务,例如:*/3 * * * * /usr/lcoal/autoRestart.sh,每3分钟执行autoRestart脚本。

 

shell脚本大致写法:

1,获取Jar包运行时所占用的进程。

2,kill掉进程。

3,加载环境变量。

4,后台重启Jar包,指定日志输出路径。

 

话不多说,直接开始整~~

一.编写可执行shell脚本

1,创建脚本文件autoRestart.sh

1 touch autoRestart.sh

2,将.sh文件变为可执行文件

chmod +x autoRestart.sh  #文件变为可执行文件,可以看到文件名变色

3,使用vim进入脚本文件,注意:shell脚本中必须要有#!/bin/bash,否则shell脚本无法执行

 1 #!/bin/bash
 2 ID=`ps -ef | grep java | grep -v 'grep' | awk '{print $2}'` #注意查询出bash本身的进程号
 3 echo $ID
 4 echo "--------------"
 5 for id in $ID
 6 do
 7 kill -9 $id
 8 echo "killed $id"
 9 done
10 sleep 2
11 echo "restart begin"
12 source /etc/profile
13 nohup java -jar /usr/local/gateway.jar > /usr/local/nohup.out &
14 processID=`ps -ef | grep java | grep -v 'grep' | awk '{print $2}'`
15 echo "restart success $processID"

 写shell脚本后,可使用 sh autoRestart.sh 或 ./autoRestart.sh 来测试一下脚本文件是否可以执行成功。

上述脚本解释:

1,查找java相关进程并取出进程号赋值给ID;

2,循环遍历变量ID,kill相关进程;

3,加载环境变量;

4,后台执行nohup java -jar 命令启动Jar包,并将日志输出到指定的nohup.out;

5,查询新启动的java进程号;

二.配置定时任务

1,编辑定时任务文件

1 crontab -e

2,添加每3min执行一次(crontab定时任务中文件需使用绝对路径)

1 */3 * * * * /usr/local/autoRestart.sh 

3,查看已配置的定时任务列表

1 crontab -l

ps.(1).重新加载crond服务

1 /sbin/service crond reload    

(2).查看定时任务执行日志

1 tail -f /var/log/cron

(3).判断语句写法格式需要注意一下:

if+空格+[+空格+表达式+空格+];then  如:

1 if [ $(ps -ef | grep java | grep -v 'grep' | wc -l) eq 25509 ];then

至此,Linux下使用shell脚本+定时任务crontab实现定时重启Jar包大功告成。。。

 

cron表达式资料:https://www.cnblogs.com/tooker/p/14666595.html

vim中复制整行、删除整行:https://www.cnblogs.com/tooker/p/14668058.html

awk简单用法:https://www.cnblogs.com/tooker/p/14677718.html

wc -l :https://www.cnblogs.com/tooker/p/14677913.html

 

 

本文参考地址:https://blog.csdn.net/weixin_39153210/article/details/98937525

https://blog.csdn.net/Tha_Real/article/details/108117612

 

本文出自作者原创,未经允许切勿转载

 

posted @ 2021-04-16 16:43  tooker  阅读(2749)  评论(0编辑  收藏  举报