Linux定时任务重启jar、docker容器

本文介绍了如何创建和配置Linux脚本来监控和重启服务。详细步骤包括编写shell脚本,设置定时任务,安装及使用lsof命令检查端口占用,以及处理docker容器的重启。此外,还涉及到了日志管理和时区设置,以及排查定时任务不执行的问题。
摘要由CSDN通过智能技术生成

原创:https://blog.csdn.net/Zhs_2000/article/details/109837996

脚本内容

#!/bin/sh
 
#切换到目录
cd /root
date=`date`
 
#查询端口占用
lsof -i:7001
 
# $? -ne 0 不存在 $? -eq 0存在 
if [ $? -ne 0 ]
then
	nohup java -Xms512m -Xmx512m -jar vehicle-7001.jar > /dev/null 2>&1 &
    echo $date  ":=============== restart ===============" >> restart.log
else
    echo $date  ":=============== is normal ==============" >> restart.log
fi

1、新建脚本并保存

vim /usr/local/monitor_restart.sh

2、新增定时任务

crontab -e
*/3 * * * * . /etc/profile;/bin/sh /usr/local/monitor_restart.sh

查看所有定时任务

crontab -l

重启crontab

service crond restart

查看日志:

tail -2 /var/log/cron

报错日志:

tail -2 /var/spool/mail/root

lsof: command not found,安装lsof

yum install lsof

定时运行命令(重启docker容器)

新增重启命令
切换到存放的路径

cd /app/myapp
vim live_restart.sh

命令内容

#!/bin/sh
 
date=`date`
 
docker restart live
echo $date  ": live restart " >> /app/myapp/live_restart.log

保存后授权

chmod 777 live_restart.sh 

测试执行一次

./live_restart.sh

查看日志,是否有执行时间的输出

cat live_restart.log

成功会显示类似:Wed Jul 14 09:41:00 CST 2021 : live restart

修改日志权限

chmod 777 live_restart.log

确保上述成功后,添加linux定时任务

crontab -e

每天凌晨2点、13点执行一次

0 2 * * * . /etc/profile;/bin/sh /app/myapp/live_restart.sh
0 13 * * * . /etc/profile;/bin/sh /app/myapp/live_restart.sh

查看所有定时任务

crontab -l

重启定时任务

service crond restart

定时任务不执行排查

1、脚本、日志是否修改了权限
2、相关路径是否是全路径
3、时区是否正确

查看定时任务状态,正常为:Active: active (running)

service crond status

查看定时任务日志

tail -100f /var/log/cron

Ubuntu系统定时任务命令为cron不是crond

service cron restart

查看当前时间

date

查看时间状态

timedatectl status

将时区设置为上海

timedatectl set-timezone "Asia/Shanghai"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值