linux ubuntu 定时任务crontab使用教程

系统 linux系统

root@iZj6cbwo06ba2g87fx63cjZ:~/demo# uname -a 
Linux iZj6cbwo06ba2g87fx63cjZ 4.4.0-117-generic #141-Ubuntu SMP Tue Mar 13 11:58:07 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

安装

apt-get install cron -y

启动

systemctl start cron

查看crontab状态
ss
编写脚本restart.sh
脚本内容如下

#! /bin/sh    
    
proc_name="trend.py"   
    
proc_num()   
{  
    num=`ps -ef | grep $proc_name | grep -v grep | wc -l`  
    return $num  
}  
  
proc_num    
number=$?
echo $number                         
if [ $number -eq 0 ]              
then                             
    cd /root/demo/ 
    #nohup python trend.py &  
    nohup /root/anaconda3/bin/python trend.py &  
fi

这里有个坑/root/anaconda3/bin/python trend.py,必须指定python版本,不然crontab执行时会随机执行一个

Python 3.7.0 (default, Jun 28 2018, 13:15:42) 
[GCC 7.2.0]

实现每秒执行一次:因为定时任务crontab最小执行单位是1min,所以在执行一次之后,每隔一秒执行一次
文件crontab.sh内容如下

#!/bin/bash 
step=1  
for (( i = 0; i < 60; i=(i+step) )); do
  /root/demo/restart.sh
  sleep $step 
done
exit 0

查看定时任务列表

crontab -l

添加定时任务列表

crontab -e

出现如下图所示内容,编辑添加 如下内容 * * * * * bash /root/demo/crontab.sh
在这里插入图片描述
然后按 Control + X,输入 Y,然后按Control + T 选择所需要保存在那个文件就可以了
DD
输入 Y,然后按Control + T
在这里插入图片描述
选择所需要保存在那个文件
在这里插入图片描述
出现这个crontab: installing new crontab就表明成功添加定时任务了

说明

crontab –e : 修改 crontab 文件. 如果文件不存在会自动创建。 
crontab –l : 显示 crontab 文件。 
crontab -r : 删除 crontab 文件。
crontab -ir : 删除 crontab 文件前提醒用户。

参考:
shell脚本:Syntax error: Bad for loop variable错误解决方法
linux定时任务crontab 实现每秒执行一次的方法
crontab定时任务不执行的原因
使用nano时怎么保存退出的问题
linux命令之crontab定时执行任务
linux服务器挂掉自动重启脚本

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章