Introduction to Crontab Usage and Common Problem Solving

 

     The Linux system is controlled by the cron (crond) system service. There is a lot of planned work on the Linux system, so this system service is started by default. In addition, since users can also set up scheduled tasks themselves, the Linux system also provides a command for users to control scheduled tasks: crontab command.


1. Introduction to crond


       The Crontab service is an industrial-grade service under Unix/Linux. Using it, you can set up periodic task execution without requiring a resident program, which has a positive effect on the high requirements of the program and the performance overhead of the system. Crontab is the main scheduling process under Unix/
Linux. It does not require manual intervention, and it allows users to submit, edit and delete corresponding tasks. In addition, each user has a Crontab file to save scheduling information, and administrators can
Disable or allow users to own Contab by editing the cron.deny and cron.allow files.
         The crontab under Linux/unix will automatically help us re-read the routine work of /etc/crontab every minute, but for some reason or other Unix/linux systems, because crontab is read into memory , so after you modify /etc/crontab, it may not run immediately, please restart the crond service at this time: /etc/init.d/crond restart.
         Crond is a daemon process used to periodically perform certain tasks or wait to process certain events under Linux. It is similar to the scheduled tasks under Windows. When the operating system is installed, the service tool will be installed by default and will start automatically. The crond process, the crond process will periodically check whether there is a task to be executed every minute, and if there is a task to be executed, the task will be executed automatically.
        Task scheduling under Linux is divided into two categories, system task scheduling and user task scheduling. System task scheduling: The work to be performed by the system periodically, such as writing cached data to the hard disk, log cleaning, etc. There is a crontab file in the /etc directory, which is the configuration file for system task scheduling.

 

2. crond service

# 安装crontab:

yum install crontabs
# 服务操作说明:

/sbin/service crond start //启动服务

/sbin/service crond stop //关闭服务

/sbin/service crond restart //重启服务

/sbin/service crond reload //重新载入配置

/sbin/service crond status //启动服务


        To check whether the crontab service has been set to start at boot, execute the command:

ntsysv

        

 

    Add the boot to start automatically:

chkconfig –level 35 crond on

 

3. Detailed explanation of crontab command

 

        1. Command format:

crontab [-u user] file

crontab [-u user] [ -e | -l | -r ]

        2. Command function:

        Through the crontab command, we can execute specified system instructions or shell script scripts at regular intervals. The unit of time interval can be minutes, hours, days, months, weeks, and any combination of the above. This command is ideal for periodic log analysis or data backup.

        3. Command parameters:

-u user:用来设定某个用户的crontab服务,例如,“-u ixdba”表示设定ixdba用户的crontab服务,
此参数一般有root用户来运行。

file:file是命令文件的名字,表示将file做为crontab的任务列表文件并载入crontab。
如果在命令行中没有指定这个文件,crontab命令将接受标准输入(键盘)上键入的命令,并将它们载入crontab。

-e:编辑某个用户的crontab文件内容。如果不指定用户,则表示编辑当前用户的crontab文件。

-l:显示某个用户的crontab文件内容,如果不指定用户,则表示显示当前用户的crontab文件内容。

-r:从/var/spool/cron目录中删除某个用户的crontab文件,如果不指定用户,则默认删除当前用户的crontab文件。

-i:在删除用户的crontab文件时给确认提示。

        4. Common method:

        1). Create a new crontab file

        Before considering submitting a crontab file to the cron process, one of the first things to do is to set the environment variable EDITOR. The cron process uses it to determine which editor to use to edit the crontab file. 99% of UNIX and LINUX users use vi, and if you do, then edit the .profile file in your $HOME directory and add this line to it:

EDITOR=vi; export EDITOR

        Then save and exit. Consider creating a file called <user> cron, where <user> is the username, for example, davecron. Add the following to this file.

# (put your own initials here)echo the date to the console every

# 15minutes between 6pm and 6am

0,15,30,45 18-06 * * * /bin/echo ‘date’ > /dev/console

        Save and exit. Make sure the first 5 fields are separated by spaces.

        In the above example, the system will output the current time to the console every 15 minutes. If the system crashes or hangs, you can see at a glance when the system stopped working from the last displayed time. In some systems, tty1 is used to represent the console, and the above example can be modified accordingly according to the actual situation. To submit the crontab file you just created, you can pass this newly created file as an argument to the cron command:

$ crontab davecron

        Now that the file has been submitted to the cron process, it will run every 15 minutes. At the same time, a copy of the newly created file has been placed in the /var/spool/cron directory, and the file name is the username (ie dave).

        2). List crontab files

        To list crontab files, use:

$ crontab -l

0,15,30,45,18-06 * * * /bin/echo `date` > dev/tty1

你将会看到和上面类似的内容。可以使用这种方法在$HOME目录中对crontab文件做一备份:

$ crontab -l > $HOME/mycron

这样,一旦不小心误删了crontab文件,可以用上述的方法迅速恢复。

        3). Edit crontab file

        If you want to add, delete or edit entries in the crontab file, and the EDITOR environment variable is set to vi, then you can use vi to edit the crontab file, the corresponding command is:

$ crontab -e

        The crontab file can be modified and exited like any other file with vi. If some entries are modified or new entries are added, cron performs the necessary integrity checks on the file when saving it. It will alert you if one of these fields has a value that is out of the allowed range.

        When editing the crontab file, new entries may be added. For example, add the following one:

# DT:delete core files,at 3.30am on 1,7,14,21,26,26 days of each month

30 3 1,7,14,21,26 * * /bin/find -name “core’ -exec rm {} \;

        Now save and exit. It's a good idea to put a comment on top of each entry in the crontab file so that you know what it does, when it runs, and most importantly, which user's job it is.

        Now let's list all its information using the crontab -l command mentioned earlier:

$ crontab -l

# (crondave installed on Tue May 4 13:07:43 1999)

# DT:ech the date to the console every 30 minites

0,15,30,45 18-06 * * * /bin/echo `date` > /dev/tty1

# DT:delete core files,at 3.30am on 1,7,14,21,26,26 days of each month

30 3 1,7,14,21,26 * * /bin/find -name “core’ -exec rm {} \;

        4). Delete the crontab file

# 要删除crontab文件,可以用:

$ crontab -r

        5). Recover lost crontab file

如果不小心误删了crontab文件,假设你在自己的$HOME目录下还有一个备份,
那么可以将其拷贝到/var/spool/cron/<username>,其中<username>是用户名。
如果由于权限问题无法完成拷贝,可以用:

$ crontab <filename>

其中,<filename>是你在$HOME目录中副本的文件名。

我建议你在自己的$ H O M E目录中保存一个该文件的副本。我就有过类似的经历,
有数次误删了crontab文件(因为r键紧挨在e键的右边)。这就是为什么有些系统文档建议不要直接编辑crontab文件,
而是编辑该文件的一个副本,然后重新提交新的文件。

有些crontab的变体有些怪异,所以在使用crontab命令时要格外小心。如果遗漏了任何选项,
crontab可能会打开一个空文件,或者看起来像是个空文件。这时敲delete键退出,不要按<Ctrl-D>,
否则你将丢失crontab文件。

5. Example of use

实例1:每1分钟执行一次command
命令:
* * * * * command
实例2:每小时的第3和第15分钟执行
命令:
3,15 * * * * command
实例3:在上午8点到11点的第3和第15分钟执行
命令:
3,15 8-11 * * * command
实例4:每隔两天的上午8点到11点的第3和第15分钟执行
命令:
3,15 8-11 */2 * * command
实例5:每个星期一的上午8点到11点的第3和第15分钟执行
命令:
3,15 8-11 * * 1 command
实例6:每晚的21:30重启smb 
命令:
30 21 * * * /etc/init.d/smb restart
实例7:每月1、10、22日的4 : 45重启smb 
命令:
45 4 1,10,22 * * /etc/init.d/smb restart
实例8:每周六、周日的1 : 10重启smb
命令:
10 1 * * 6,0 /etc/init.d/smb restart
实例9:每天18 : 00至23 : 00之间每隔30分钟重启smb 
命令:
0,30 18-23 * * * /etc/init.d/smb restart
实例10:每星期六的晚上11 : 00 pm重启smb 
命令:
0 23 * * 6 /etc/init.d/smb restart
实例11:每一小时重启smb 
命令:
* */1 * * * /etc/init.d/smb restart
实例12:晚上11点到早上7点之间,每隔一小时重启smb 
命令:
* 23-7/1 * * * /etc/init.d/smb restart
实例13:每月的4号与每周一到周三的11点重启smb 
命令:
0 11 4 * mon-wed /etc/init.d/smb restart
实例14:一月一号的4点重启smb 
命令:
0 4 1 jan * /etc/init.d/smb restart
实例15:每小时执行/etc/cron.hourly目录内的脚本
命令:
01 * * * * root run-parts /etc/cron.hourly


Note:
run-parts is the parameter. If you remove this parameter, you can write the name of a script to run instead of the directory name.

sh脚本文件:test.sh

#! /bin/sh

su - oracle << EOF

sqlplus test/test@test @"test.sql"

sql脚本文件:test.sql

insert into test_tb values (sysdate);

crontab文件:

0,15,30,45 * * * * /apps/bin/test.sh
附crontab规则详细实例

1、每天6:00执行

0 6 * * * root /home/mvp/osyunwei.sh

2、每周六凌晨4:00执行

0 4 * * 6 root /home/mvp/osyunwei.sh

3、每周六凌晨4:05执行

5 4 * * 6 root /home/mvp/osyunwei.sh 

4、每周六凌晨4:15执行

15 4 * * 6 root /home/mvp/osyunwei.sh

5、每周六凌晨4:25执行

25 4 * * 6 root /home/mvp/osyunwei.sh

6、每周六凌晨4:35执行

35 4 * * 6 root /home/mvp/osyunwei.sh

7、每周六凌晨5:00执行

5 * * 6 root /home/mvp/osyunwei.sh

8、每天8:40执行

40 8 * * * root /home/mvp/osyunwei.sh

9、每天8:30执行

30 8 * * * root /home/mvp/osyunwei.sh

10、每周一到周五的11:41开始,每隔10分钟执行一次    #值得借鉴

41,51 11 * * 1-5   root /home/mvp/osyunwei.sh

或者

1-59/10 12-23 * * 1-5   root /home/mvp/osyunwei.sh

11、在每天的10:31开始,每隔2小时重复一次

31 10-23/2 * * * root   /home/mvp/osyunwei.sh

12、每天15:00执行

0 15 * * *  root /home/mvp/osyunwei.sh

13、每天的10:30开始,每隔2小时重复一次

30 10-23/2 * * * root  /home/mvp/osyunwei.sh

14、每天15:30执行

30 15 * * *  root /home/mvp/osyunwei.sh

15、每天17:50执行

50 17 * * *  root /home/mvp/osyunwei.sh

16、每天8:00执行

0 8 * * *  root  /home/mvp/osyunwei.sh

17、每天18:00执行

0 18 * * *  root  /home/mvp/osyunwei.sh

18、每天8:30执行

30 8 * * *  root  /home/mvp/osyunwei.sh

19、每天20:30

30 20 * * *  root /home/mvp/osyunwei.sh

20、每周一到周五2:00

0 2 * * 1-5 root /home/mvp/osyunwei.sh

21、每周一到周五9:30

30 9 * * 1-5 root /home/mvp/osyunwei.sh

22、每周一到周五8:00,每周一到周五9:00

0 8,9 * * 1-5  root /home/mvp/osyunwei.sh

23、每天23:59

59 23 * * *  root  /home/mvp/osyunwei.sh

24、每周六23:59

59 23 * * 6  root    /home/mvp/osyunwei.sh

25、每天0:30

30 0 * * *  root  /home/mvp/osyunwei.sh

26、每周一到周五9:25到11:35之间、13:00到15:00之间,每隔10分钟运行一次

分区段写值得借鉴

25,35,45,55  9 * * 1-5  root   /home/mvp/osyunwei.sh

5-59/10  10 * * 1-5  root   /home/mvp/osyunwei.sh

5,15,25,35  11 * * 1-5  root   /home/mvp/osyunwei.sh

*/10  13-15 * * 1-5  root   /home/mvp/osyunwei.sh

27、每周一到周五8:30、8:50、9:30、10:00、10:30、11:00、11:30、13:30、14:00、14:30、5:00分别执行一次

30,50 8 * * 1-5  root  /home/mvp/osyunwei.sh

30 9 * * 1-5  root  /home/mvp/osyunwei.sh

*/30 10-11 * * 1-5  root  /home/mvp/osyunwei.sh

30 13 * * 1-5  root  /home/mvp/osyunwei.sh

0,30 14-15 * * 1-5  root  /home/mvp/osyunwei.sh

28、每天23:50执行

50 23 * * *  root  /home/mvp/osyunwei.sh

29、每天10:00、16:00执行

0 10,16 * * *  root /home/mvp/osyunwei.sh

30、每天5:30执行

30 5 * * *  root  /home/mvp/osyunwei.sh

31、每周一到周五9:30执行

30 9 * * 1-5  root  /home/mvp/osyunwei.sh

32、每周一到周五13:00执行

0 13 * * 1-5  root  /home/mvp/osyunwei.sh

33、每天7:51执行

51 7 * * *  root /home/mvp/osyunwei.sh

34、每天7:53、12:40分别执行一次

53 7 * * *  root /home/mvp/osyunwei.sh

40 12 * * *  root /home/mvp/osyunwei.sh

35、每天7:55执行

55 7 * * *  root  /home/mvp/osyunwei.sh

36、每天8:10、16:00、20:00分别执行一次

10 8 * * *  root  /home/mvp/osyunwei.sh

0 16 * * *  root  /home/mvp/osyunwei.sh

0 20 * * *  root  /home/mvp/osyunwei.sh

37、每天7:57、8:00分别执行一次

57 7 * * *  root  /home/mvp/osyunwei.sh

0 8 * * *  root  /home/mvp/osyunwei.sh


4. Precautions for use

 

        1. Pay attention to the problem of environment variables
        Sometimes we create a crontab, but this task cannot be executed automatically, but there is no problem in executing this task manually. This situation is generally caused by not configuring environment variables in the crontab file.

        When defining multiple scheduling tasks in the crontab file, one issue that needs special attention is the setting of environment variables, because when we manually execute a task, it is performed in the current shell environment. Of course, the program can find the environment variables, while the system When automatically executing task scheduling, no environment variables are loaded. Therefore, it is necessary to specify all the environment variables required for task running in the crontab file, so that there is no problem when the system executes task scheduling.

        Don't assume cron knows about the special environment it needs, it doesn't. So you want to make sure to provide all the necessary paths and environment variables in the shelll script, except for some global variables that are automatically set. So pay attention to the following 3 points:

        1) Write the global path when the file path is involved in the script;

        2) When java or other environment variables are used for script execution, environment variables are introduced through the source command, such as:

cat start_jboss.sh

#!/bin/sh

source /etc/profile

export RUN_CONF=/home/redhat/conf/platform/cbp/cbp_jboss.conf

/usr/local/jboss-7.0.5/bin/run.sh -c mev &

        3) When the manual execution of the script is OK, but the crontab is not executed. At this time, you must boldly suspect that the environment variable is to blame, and you can try to directly introduce the environment variable in crontab to solve the problem. Such as:

0 * * * * . /etc/profile;/bin/sh /var/www/java/test/bin/restart_audit_test.sh

        Pay attention to cleaning the logs of system users. After each task is scheduled and executed, the log information will be very large over time, which may affect the normal operation of the system. Therefore, it is very important to redirect each task.

        For example, the following form can be set in the crontab file to ignore log output:

0 */3 * * * /usr/local/apache2/apachectl restart >/dev/null 2>&1

        "/dev/null 2>&1" means that the standard output is redirected to /dev/null first, and then the standard error is redirected to the standard output. Since the standard output has been redirected to /dev/null, the standard error will also be redirected. Directed to /dev/null, so the log output problem is solved.

        2. System-level task scheduling and user-level task scheduling
        System-level task scheduling mainly completes some maintenance operations of the system, and user-level task scheduling mainly completes some user-defined tasks, which can be completed by placing user-level task scheduling in system-level task scheduling (It is not recommended to do this), but the reverse is not possible. The task scheduling operation of the root user can be set by "crontab -uroot -e", or the scheduling task can be directly written to the /etc/crontab file. It should be noted that, If you want to define a task to restart the system regularly, you must put the task in the /etc/crontab file, even if you create a task to restart the system regularly under the root user, it is invalid.

        3. Other precautions
        The newly created cron job will not be executed immediately, and it will take at least 2 minutes to execute. If you restart cron, it will be executed immediately. When crontab suddenly fails, you can try /etc/init.d/crond restart to solve the problem. Or check the log to see if a job is executed/errored tail -f /var/log/cron.

千万别乱运行crontab -r。它从Crontab目录(/var/spool/cron)中删除用户的Crontab文件。
删除了该用户的所有crontab都没了。

        In crontab, % has a special meaning, which means newline. If you want to use it, you must escape \%. For example, the frequently used date '+%Y%m%d' will not be executed in crontab, it should be replaced with date '+\%Y\%m\%d' .

crontab -l  列出当前登录用户所有定时任务
crontab -l -u XXX  列出XXX用户的所有定时任务,如有没有会提示 no crontab for XXX
crontab -e  编辑当前用户的定时任务
crontab -r  删除当前用户的定时任务
 
查看crontab的执行情况:  tail -f /var/log/cron
查看crontab的执行log:vim /var/spool/mail/root
每日生成一个以时间命名的log文件
#!/bin/bash
echo "Spring Cloud - 收付 - 清空日志"
var=`date +%Y-%m-%d`
cd /home/redhat/SpringBoot/
zip -r nohup.out.$var.zip nohup.out
cp /dev/null nohup.out 


        4. Time settings for scheduled tasks

* * * * *               每分钟执行
*/1 * * * *           每分钟执行
0 5 * * *                每天五点执行
0-59/2 * * * *        每隔两分钟执行,且是偶数分钟执行,比如2,4,6
1-58/2 * * * *        每隔两分钟执行,且是奇数分钟执行,比如3,5,7
0 0 1,5,10 * *        每个月1号,5号,10号执行
0 0 1-5 * *            每个月 1到5号执行

minute: 表示分钟,可以是从0到59之间的任何整数。

hour:表示小时,可以是从0到23之间的任何整数。

day:表示日期,可以是从1到31之间的任何整数。

month:表示月份,可以是从1到12之间的任何整数。

week:表示星期几,可以是从0到7之间的任何整数,这里的0或7代表星期日。

command:要执行的命令,可以是系统命令,也可以是自己编写的脚本文件。

 

Five, CRONTAB grammar and application

 

        1. View the scheduled tasks of the current user

[oracle@localhost ~]$ crontab -l

* * * * * /home/oracle/test.sh >/dev/null 2>&1

        2. Edit the current user's scheduled task

可以在编辑状态修改、删除、新增一些定时任务。注释一般用#

[oracle@localhost ~]$ crontab -e

        3. Delete the current user's scheduled task

[root@localhost ~]# crontab -r

[root@localhost ~]# crontab -l

no crontab for root

        4. As shown below, the format of the scheduled task in the general crontab file is as follows:

59 23 * * * /home/oracle/scripts/alert_log_archive.sh >/dev/null 2>&1

crontab 文件中每个条目中各个域的意义和格式:

第一列 分钟: 1——59

第二列 小时: 1——23(0表示子夜)

第三列 日 : 1——31

第四列 月 : 1——12

第五列 星期: 星期0——6(0表示星期天,1表示星期一、以此类推)

第六列 要运行的命令

 

        6. You can view the crontab manual online

$man crontab | more

        

7. Reasons and solutions for crontab not executing


        First of all, it must be determined whether the script is written correctly and whether the shell script has execution permission. If everything is normal and still cannot be executed, use the following method:

# 使root用户的crontab生效
crontab -u root /var/spool/cron/root

# 重启crontab服务
service crond restart

 

        Error example one:

"cronfile1":2: premature EOF
errors in crontab file, can"t install.
在crontab文件末尾增加一个空行就可解决此问题。

        Error example two:

"/tmp/crontab.NINM91":2: bad day-of-week
errors in crontab file,can"t install

根据提示,是第二行的 周写错了

crontab -e保存时,crond会检测时间格式,如果时间格式不正确就会报错errors in crontab file,can’t install,还是一个很人性化的设置。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325481869&siteId=291194637