zoukankan      html  css  js  c++  java
  • Crontab

    Crontab介绍

    Crontab是linux系统用来定期执行命令或程序的工具。

    两种任务创建方式

      (系统级的)做系统级配置我们会直接配置 /etc/crontab  /etc/cron.d/

      (用户级的)一般还是建议大家使用 crontab -e ,这样系统也会帮着检查我们配置的脚本语法。

    定期自动运行脚本

      也可以直接将需要定期执行的脚本放入以下目录中:

        /etc/cron.hourly/    # 被定义在 /etc/cron.d/0hourly 中每小时自动调用

        /etc/cron.daily/      # 被定义在 /etc/anacrontab 中每天自动调用

        /etc/cron.weekly/     # 被定义在 /etc/anacrontab 中每周自动调用

        /etc/cron.monthly/     # 被定义在 /etc/anacrontab 中每月自动调用

         

    示例: logrotate 每天自动运行的脚本

    [root@servera cron.d]# cd /etc/cron.daily/
    [root@servera cron.daily]# ls
    logrotate  rhsmd
    [root@servera cron.daily]# cat logrotate 
    #!/bin/sh
    
    /usr/sbin/logrotate /etc/logrotate.conf
    EXITVALUE=$?
    if [ $EXITVALUE != 0 ]; then
        /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
    fi
    exit $EXITVALUE

    命令 Crontab

    Usage:
    crontab [options] file
    crontab [options]
    crontab -n [hostname]

    Options:
    -u <user> define user
    -e edit user's crontab  # 以user名称保存路径 /var/spool/cron/
    -l list user's crontab
    -r delete user's crontab
    -i prompt before deleting
    -n <host> set host in cluster to run users' crontabs
    -c get host in cluster to run users' crontabs
    -s selinux context
    -V print version and exit
    -x <mask> enable debugging

    Contab语法

    # 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

    *    号表示任意时间都执行。

    -    减号,表示分隔符,表示一个时间范围,区间段,如17-19点,每天的17,18,19点的00分执行任务。

    ,   逗号,表示分隔时段的意思。30 17,18,19 * * * /bin/sh /scripts/test.sh 表示每天17、18、19点的半点时刻执行/scripts/test.sh脚本。

    /n   n代表数字,即“每个n单位时间”,例如:每10分钟执行一次任务,可以写成*/10 * * * * cmd,其中*/10的意思是每10分钟执行cmd命令。

    书写定时任务的若干要领方法

    要领1:为定时任务规则加必要的注释

    要领2:定时任务命令或程序最好写到脚本里执行

    要领3:执行shell脚本任务前加/bin/sh

    要领4:定时任务执行的脚本要规范路径(/service/scripts)

    要领5:定时任务命令或脚本结尾加>/dev/null 2>&1

    具体例子:

    ● 0 */2 * * * /sbin/service httpd restart 意思是每两个小时重启一次apache

    ● 50 7 * * * /sbin/service sshd start 意思是每天7:50开启ssh服务

    ● 50 22 * * * /sbin/service sshd stop 意思是每天22:50关闭ssh服务

    ● 0 0 1,15 * * fsck /home 每月1号和15号检查/home 磁盘

    查看Log

    /var/log/cron

  • 相关阅读:
    linux 查看 服务 命令
    Java Swing中键盘事件的处理(转)
    VI常用命令及快捷键(转)
    Linux source用法(转)
    无线桥接 WDS 中继(转)
    在远程桌面连接中使用任务管理器(转)
    linux 运行 级别(转)
    linux 当前用户 命令 w who(转)
    vecket适合和不适合的10种人(转)
    在查找预编译头使用时跳过解决(转)
  • 原文地址:https://www.cnblogs.com/vincenshen/p/6559610.html
Copyright © 2011-2022 走看看