(JAVA) Linux定时重启sh脚本
1.编写sh脚本
#!/bin/bash
export LANG=en_US.UTF-8
#jar包名字。
JAR_NAME=demo.jar
project_directory=/project/
APP_NAME=$project_directory$JAR_NAME
JVM="-Xms512m -Xmx4096m -XX:PermSize=256m -XX:MaxPermSize=1024m -XX:MaxNewSize=512m"
APPFILE_PATH='-Dspring.config.location='$project_directory'application-dev.yml'
#停掉procuratorate服务
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]------获取demo进程号" >> $project_directory'start-log/start-desp.log'
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}'`
# 这里判断procuratorate进程是否存在
if [ $pid ];then
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]------停止demo进程" >> $project_directory'start-log/start-desp.log'
kill -9 $pid
k=$?
if [ $k -eq 0 ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]------demo停止成功啦!" >> $project_directory'start-log/start-desp.log'
source /etc/profile;
nohup java $JVM -jar $APPFILE_PATH $APP_NAME > $project_directory'start-log/nohup-'$(date '+%Y%m%d%H%M%S')'.out' 2>&1 &
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]------demo启动成功啦!" >> $project_directory'start-log/start-desp.log'
else
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]------demo停止失败..." >> $project_directory'start-log/start-desp.log'
fi
else
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO]------demo没有运行..." >> $project_directory'start-log/start-desp.log'
fi
解决执行脚本 ‘/r’ 报错
sed -i 's/\r//' **.sh
2.配置定时任务
-
sh脚本赋予u+x权限
-
控制台输入crontab -e命令
-
文件内容加入表达式
# /project/restart.sh为脚本绝对路劲 * 0 * * 1 sh /project/restart.sh
-
重启定时服务
/bin/systemctl restart crond.service
-
查看任务执行记录
tail -f /var/log/cron
3.日志清理:Linux清理文件夹下超过N时间的文件
#!/bin/bash
log_base_path=/project
log_console_log_path=${log_base_path}/start-log
JAVA_JAR=procuratorate-server
echo `date '+%Y-%m-%d %H:%M:%S'`"清理日志脚本开始执行>>>>>>>>>>>>>>>>>>>>>>>">>${JAVA_JAR}
cd $log_console_log_path //清理/project下start-log-开头的文件
//. 表示当前目录 -type f:
//指定查找对象为文件 -name *.log:
//指定查找对象名称以.log结尾 -mtime +10:
//查找10天以前的老文件 -mmin +120:
find ./ -name 'start-log-*.log' -mmin +20 -exec rm {} \;
echo `date '+%Y-%m-%d %H:%M:%S'`"清理日志脚本执行结束>>>>>>>>>>>>>>>>>>>>>>>">>${JAVA_JAR}
4.Linux 开机执行命令
编辑/etc/rc.local 文件
vim /etc/rc.local
在文件底部加入需要执行的命令,示例如下:
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
/usr/bin/vmhgfs-fuse .host:/ /mnt/win -o subtype=vmhgfs-fuse,allow_other #示例
保存,reboot 重启,查看命令是否正常执行。
如果命令没有正常执行,可能是未设置/etc/rc.local 文件的执行权限:
chmod +x /etc/rc.local
再次重启,就可以正常自动执行了。