前言
Linux 使用 crontab 添加定时任务
提示:以下是本篇文章正文内容,下面案例可供参考
一、环境准备
先安装;
启用:systemctl enable crond
启动:systemctl start crond
停止:systemclt stop crond
查看运行日志:sudo tail -f /var/log/cron
crontab [-u username] //省略用户表表示操作当前用户的crontab
-e (编辑工作表)
-l (列出工作表里的命令)
-r (删除工作作)
时间配置:https://www.runoob.com/w3cnote/linux-crontab-tasks.html
二、使用
修改配置文件
[root@iZ8vbada19ftokjkadc64aZ kafka]# vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
*/1 * * * * root sh /opt/kafka/check_kafka.sh #每分钟执行一次
check_kafka 脚本
#!/bin/sh
source /etc/profile
proc_num(){
num=`ps -ef | grep "kafka.Kafka" | grep -v grep | wc -l` #计算进程数
return $num
}
proc_num
number=$?
echo $number
if [ $number -eq 0 ]
then
#清理消息文件
sudo rm -rf /opt/kafka/logs/vm*
#执行重启命令
nohup /opt/kafka/bin/./kafka-server-start.sh /opt/kafka/config/server.properties 1>/dev/null 2>&1 &
#写入重启日志
echo "$(date)--server down restart..." >> /opt/kafka/kafka_restart.log
fi
:<<!
# 获取pid
proc_id(){
pid=(`ps -ef | grep "/data/kafka/kafka/kafka/bin/" | grep -v grep | awk '{print $2}'`)
return $pid
}
proc_id
pid=$?
echo ${pid[1]}
!