crontab 命令详解

| 选择喜欢的代码风格  

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

crontab 命令安装:


-bash: crontab: command not found

#Winddows ( WSL 2 )
sudo apt-get update sudo 
apt-get install bcron

#Debian
apt-get install bcron

#Ubuntu
apt-get install bcron

#Arch Linux
pacman -S cronie

#Kali Linux
apt-get install systemd-cron

#CentOS
yum install cronie

#Fedora
dnf install cronie

#Raspbian
apt-get install interchange

#Dockerfile
dockerfile.run/crontab

crontab 命令语法:


crontab [-u user] file
crontab [-u user] [-l | -r | -e] [-i] [-s]

  1 SHELL=/bin/bash
  2 PATH=/sbin:/bin:/usr/sbin:/usr/bin
  3 MAILTO=root
  4 HOME=/
  5 
  6 # For details see man 4 crontabs
  7 
  8 # Example of job definition:
  9 # .---------------- minute (0 - 59)
 10 # |  .------------- hour (0 - 23)
 11 # |  |  .---------- day of month (1 - 31)
 12 # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
 13 # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,s
    at
 14 # |  |  |  |  |
 15 # *  *  *  *  * user-name command to be executed
 16 

#man crontab
[root@Dev_Test etc]$man crontab
CRONTAB(1)                   Cronie Users’ Manual                   CRONTAB(1)

NAME
       crontab - maintain crontab files for individual users

SYNOPSIS
       crontab [-u user] file
       crontab [-u user] [-l | -r | -e] [-i] [-s]

DESCRIPTION
       Crontab  is  the program used to install, remove or list the tables used
       to drive the cron(8) daemon.  Each user can have their own crontab,  and
       though  these  are  files  in  /var/spool/ , they are not intended to be
       edited directly. For SELinux in mls mode can be even more crontabs - for
       each range. For more see selinux(8).

       The  cron jobs could be allow or disallow for different users. For clas-
       sical  crontab  there  exists  cron.allow  and  cron.deny   files.    If
       cron.allow  file  exists, then you must be listed therein in order to be
       allowed to use this command.  If the cron.allow file does not exist  but
       the  cron.deny  file  does  exist,  then  you  must not be listed in the
       cron.deny file in order to use this command.  If neither of these  files
       exists,  only  the  super user will be allowed to use this command.  The
       second option is using PAM authentication, where you set up users, which
       could   or   couldn’t  use  crontab  and  also  system  cron  jobs  from
       /etc/cron.d/.

       The temporary directory could be set in enviroment  variables.  If  it’s
       not set by user than /tmp is used.

OPTIONS
       -u     Append  the  name of the user whose crontab is to be tweaked.  If
              this option is not given, crontab examines "your" crontab,  i.e.,
              the crontab of the person executing the command.  Note that su(8)
              can confuse crontab and that if you are running inside  of  su(8)
              you should always use the -u option for safety’s sake.  The first
              form of this command is used to install a new crontab  from  some
              named file or standard input if the pseudo-filename "-" is given.

       -l     The current crontab will be displayed on standard output.

       -r     The current crontab will be removed.

       -e     This option is used to edit the current crontab using the  editor
              specified  by  the VISUAL or EDITOR environment variables.  After
              you exit from the editor, the modified crontab will be  installed
              automatically.

       -i     This option modifies the -r option to prompt the user for a ’y/Y’
              response before actually removing the crontab.

       -s     It will append the current SELinux security context string as  an
              MLS_LEVEL  setting  to the crontab file before editing / replace-
              ment occurs - see the documentation of MLS_LEVEL in crontab(5).

SEE ALSO
       crontab(5),cron(8)

FILES
       /etc/cron.allow
       /etc/cron.deny

STANDARDS
       The crontab command conforms to IEEE Std1003.2-1992  (‘‘POSIX’’).   This
       new command syntax differs from previous versions of Vixie Cron, as well
       as from the classic SVR3 syntax.

DIAGNOSTICS
       A fairly informative usage message appears if you run it with a bad com-
       mand line.

AUTHOR
       Paul Vixie 

Marcela Mašláňová                20 July 2009                       CRONTAB(1)

crontab 命令选项:


-e:编辑该用户的计时器设置;
-l:列出该用户的计时器设置;
-r:删除该用户的计时器设置;
-u<用户名称>:指定要设定计时器的用户名称。

crontab 命令参数:


crontab 文件:指定包含待执行任务的 crontab 文件。

crontab 补充说明:


crontab命令 被用来提交和管理用户的需要周期性执行的任务,与 Windows 下的 Task 计划任务类似,当安装完成操作系统后,默认会安装此服务工具,并且会自动启动 crond 进程,crond 进程每分钟会定期检查是否有要执行的任务,如果有要执行的任务,则自动执行该任务。

crontab 命令知识扩展:


Linux下的任务调度分为两类: 系统任务调度用户任务调度

系统任务调度: 系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等。在 /etc/ 目录下有一个 crontab 文件,这个就是系统任务调度的配置文件。

/etc/crontab 文件包括下面几行

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""
HOME=/

# run-parts
51 * * * * root run-parts /etc/cron.hourly
24 7 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

前四行是用来配置crond任务运行的环境变量,第一行SHELL变量指定了系统要使用哪个 shell,这里是 bash,第二行 PATH 变量指定了系统执行命令的路径,第三行 MAILTO 变量指定了 crond 的任务执行信息将通过电子邮件发送给 root 用户,如果 MAILTO 变量的值为空,则表示不发送任务执行信息给用户,第四行的 HOME 变量指定了在执行命令或者脚本时使用的主目录。

用户任务调度: 用户定期要执行的工作,比如用户数据备份、定时邮件提醒等。用户可以使用 crontab 工具来定制自己的计划任务。所有用户定义的crontab文件都被保存在/var/spool/cron目录中。其文件名与用户名一致,使用者权限文件如下:

/etc/cron.deny     #该文件中所列用户不允许使用crontab命令
/etc/cron.allow    #该文件中所列用户允许使用crontab命令
/var/spool/cron/   #所有用户crontab文件存放的目录,以用户名命名

crontab文件的含义:用户所建立的crontab文件中,每一行都代表一项任务,每行的每个字段代表一项设置,它的格式共分为六个字段,前五段是时间设定段,第六段是要执行的命令段,格式如下:

minute   hour   day   month   week   command     #顺序:分 时 日 月 周

其中:

  1. minute: 表示分钟,可以是从0到59之间的任何整数。
  2. hour:表示小时,可以是从0到23之间的任何整数。
  3. day:表示日期,可以是从1到31之间的任何整数。
  4. month:表示月份,可以是从1到12之间的任何整数。
  5. week:表示星期几,可以是从0到7之间的任何整数,这里的0或7代表星期日。
  6. command:要执行的命令,可以是系统命令,也可以是自己编写的脚本文件。

在以上各个字段中,还可以使用以下特殊字符

  • 星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满足其它字段的制约条件后每月都执行该命令操作。
  • 逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”
  • 中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”
  • 正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。

crond服务

/sbin/service crond start    //启动服务
/sbin/service crond stop     //关闭服务
/sbin/service crond restart  //重启服务
/sbin/service crond reload   //重新载入配置

查看crontab服务状态:

[root@Dev_Test etc]$service crond status
crond (pid  2735) is running...

手动启动crontab服务:

service crond start

查看crontab服务是否已设置为开机启动,执行命令:

ntsysv

加入开机自动启动:

chkconfig –level 35 crond on

crontab 命令实例:


每1分钟执行一次command

* * * * * command

每小时的第3和第15分钟执行

3,15 * * * * command

在上午8点到11点的第3和第15分钟执行

3,15 8-11 * * * command

每隔两天的上午8点到11点的第3和第15分钟执行

3,15 8-11 */2 * * command

每个星期一的上午8点到11点的第3和第15分钟执行

3,15 8-11 * * 1 command

每晚的21:30重启smb

30 21 * * * /etc/init.d/smb restart

每月1、10、22日的4 : 45重启smb

45 4 1,10,22 * * /etc/init.d/smb restart

每周六、周日的1:10重启smb

10 1 * * 6,0 /etc/init.d/smb restart

每天18 : 00至23 : 00之间每隔30分钟重启smb

0,30 18-23 * * * /etc/init.d/smb restart

每星期六的晚上11:00 pm重启smb

0 23 * * 6 /etc/init.d/smb restart

每一小时重启smb

* */1 * * * /etc/init.d/smb restart

晚上11点到早上7点之间,每隔一小时重启smb

* 23-7/1 * * * /etc/init.d/smb restart

每月的4号与每周一到周三的11点重启smb

0 11 4 * mon-wed /etc/init.d/smb restart

一月一号的4点重启smb

0 4 1 jan * /etc/init.d/smb restart

每小时执行/etc/cron.hourly目录内的脚本

01 * * * * root run-parts /etc/cron.hourly

crontab 命令的坑:


注意:crontab里执行命令是没有PATH环境变量一说的,所以必须写绝对路径,否则crontab是找不到命令的..

注意 crontab 两个大坑和一个超级大坑!

之前crontab是这样写的:

* * * mysqldump -u user -pxxxx database > "/alidata/backup/imyzf.com/$(date +%F\ %T).sql"

1 首先,是百分号(%)

在crontab -e中输入的命令里,第一个%会被认为是标准输入的开始,接下来的%都会被认为是换行。所以在这里原本只是格式化日期的%被当成了标准输入,命令就出问题了。解决方案有两种,一是用sed命令;我采用了另外一种方法,把命令写到了sh文件里(为什么?因为还有一个大坑)。

2 然后,是环境变量

即使解决了上面的问题,还是不能正常执行任务,因为 crontab 的环境变量是另外定义的。通过 cat /etc/crontab 你会发现默认的PATH是 /sbin:/bin:/usr/sbin:/usr/bin,而我们的 mysqldump 是在 /alidata/server/mysql/bin里的。

所以要修改默认设置,或者简单点,在 sh 文件里另外加上一行修改 PATH,最后成了这样:

#!/bin/bash
PATH="$PATH:/alidata/server/mysql/bin"
mysqldump -u user -pxxxx database > "/alidata/backup/www.pianyiwan.com/$(date +%F\ %T).sql"

然后,我的crontab写成了这样(使用/dev/null是为了丢弃mysqldump使用标准输出的提示):

* * * /alidata/backup/www.pianyiwan.com/backup.sh > /dev/null 2>&1

注意 crontab 的超级大坑来了;

突然发现 crontab 内容丢失了,或者是被清空了:是什么原因造成的?

坑一:If you issue crontab without any option and then press ctrl-d, it will erase everything in your crontab -- 如果你不带参数运行 crontab 命令,然后按了 Ctrl+D,则 crontab 内容会被清空!!!这时候退出要用 Ctrl+C切记!!!

坑二:看了 man crontab 手册,如果执行 crontab -r,则 crontab 内容会被清空————如果将 crontab -e 敲成了 crontab -r ,内容也没了,er 的位置很近……是不是很坑!

找回丢失的 crontab 内容


crontab有运行日志,在日志里面可以找到执行过的历史命令。前提是要有root权限。命令如下:

cat /var/log/cron* | grep -i "`which cron`" > ./all_temp

cat  ./all_temp | grep -v "" > ./cmd_temp

用awk读取cmd_temp,即可得到命令。

[script-02 tmp]$ cat cmd_temp  | grep username | awk -F 'CMD' '{print $2}' | sort | uniq

(bash   /home/appadmin/script/security/auto_restart.sh)

命令是找回了,可是执行周期呢?可以通过查看执行历史,如果看到是一分钟一次,则可以判断执行周期。总结:平时注意备份 crontab 配置!

还有一个大坑:执行 crontab 有时候不注意,有可能会导致磁盘 inodes 被耗尽的情况,具体情况及解决方案,请移步下面网址查看:

传坑门: No space left on device:Inode 已耗尽

crontab 扩展阅读:




crontab 命令评论