zoukankan      html  css  js  c++  java
  • centos crontab定时任务用法

    一、安装crond服务

    yum -y update
    yum -y install cronie yum-cron

     

    二、crontab任务语法

    crontab任务配置基本格式:
    *   *  *  *  *  command
    第1列表示分钟0~59 每分钟用 * 或者 */1 表示
    第2列表示小时0~23(0表示0点)
    第3列表示日期1~31
    第4列表示月份1~12
    第5列标识号星期0~60,7都可表示星期天)
    第6列要运行的命令或执行shell脚本

    综合起来就是: 分钟(0-59) 小时(0-23) 日期(1-31) 月份(1-12) 星期(0-6,0代表星期天)  命令

    从上面可以看出,crontab最小的时间单位: 1分钟。如果要每30秒执行一次脚本,要么写个小脚本,要么在crontab增加延迟。

    例子:crontab中增加延迟30秒来实现

    a、crontab -e,添加如下内容:
    */1 * * * * sh && echo "dd" >> /logs/cron-cc.log
    */1 * * * * sleep 30 && echo "cc" >> /logs/cron-cc.log
    
    b、重启crond
    systemctl reload crond
    systemctl restart crond
    
    c、查看当前用户定时任务
    crontab -l
    
    d、通过日志查看是否生效
    tail -f /logs/cron-cc.log

     

    案例一:每隔10秒执行一次

    ##crontab设置的最小时间为每分钟,实现以秒为单位进行定时任务执行。

    */1 * * * * sh /root/shell/aa.sh
    */1 * * * * sleep 10 && sh /root/shell/aa.sh
    */1 * * * * sleep 20 && sh /root/shell/aa.sh
    */1 * * * * sleep 30 && sh /root/shell/aa.sh
    */1 * * * * sleep 40 && sh /root/shell/aa.sh
    */1 * * * * sleep 50 && sh /root/shell/aa.sh

    注意:aa.sh为执行脚本


    案例二:每隔20秒执行一次

    */1 * * * * sh /root/shell/aa.sh
    */1 * * * * sleep 20 && sh /root/shell/aa.sh
    */1 * * * * sleep 40 && sh /root/shell/aa.sh

    注意:aa.sh为执行脚本

    案例三:每隔5分钟执行一次

    */5 * * * * sh /root/shell/echo.sh


    三、crontab常用命令

    ##查看当前用户定时任务
    crontab -l 
    调用/var/spool/cron/目录下相关用户的定时任务信息
    
    查看定时任务日志
    tail -f /var/log/cron
    
    systemctl status crond.service
    systemctl start crond.service
    systemctl stop crond.service
    systemctl restart crond.service
    systemctl reload crond.service
    
    
    把cron服务加入linux开机自启动
    systemctl enable crond.service
    systemctl is-enabled crond.service
    
    #crond后台的工作情况并过滤出来
    ps -ef |grep crond|grep -v grep

     注意:

    路径问题

    有些脚本涉及到文件操作,文件路径不正确也会导致脚本无法正常执行,建议使用绝对路径,或者在执行脚本时,先进入该脚本的路径下,在执行。Crontab的command配置如下:

    */1 * * * * cd /root/shell && ./cron.sh
  • 相关阅读:
    非系统服务如何随系统启动时自动启动(rc.local加了可执行权限,仍然没有生效)
    centos7安装部署mysql5.7服务器
    centos7配置openldap服务器
    MySQL之高可用MHA部署
    root用户登录mysql后新建用户提示1045错误
    centos7上部署vnc服务器并实现远程桌面
    xenserver开启虚拟机时提示找不到存储介质,强制关闭和重启都没用
    固态硬盘和机械硬盘双硬盘安装win10,提示无法找到系统
    centos7安装的mysql无法启动(mysql daemon failed to start)
    实现在同一界面打开putty终端连接工具
  • 原文地址:https://www.cnblogs.com/linjiqin/p/11720673.html
Copyright © 2011-2022 走看看