Crontab command details

Source: Internet
Author: User

Crontab command details

I,Crond Introduction

Crond is a daemon in linux that is used to periodically execute a task or wait for processing some events. It is similar to a scheduled task in windows. After the operating system is installed, by default, the service tool is installed and the crond process is automatically started. The crond Process regularly checks whether there are tasks to be executed every minute. If there are tasks to be executed, the task is automatically executed.

In Linux, task scheduling is divided into two types: System Task Scheduling and user task scheduling.

System Task Scheduling: the tasks that the system periodically performs, such as writing cached data to the hard disk and clearing logs. There is a crontab file under the/etc directory, which is the configuration file for system task scheduling.

The/etc/crontab file contains the following lines:

[Root @ localhost ~] # Cat/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

[Root @ localhost ~] #

 

The first four rows are used to configure the environment variables for running crond tasks. The first line of SHELL variables specifies the shell to be used by the system. bash is used here, the PATH variable in the second line specifies the PATH for the system to execute the command. The MAILTO variable in the third line specifies that the crond task execution information will be sent to the root user by email. If the value of MAILTO variable is null, the task execution information is not sent to the user. The HOME variable in the fourth line specifies the main directory used for executing commands or scripts. The meaning of the lines 6 to 9 will be detailed in the next section. I will not talk about it here.

User task scheduling: jobs that you regularly perform, such as user data backup and scheduled email reminders. You can use the crontab tool to customize your own scheduled tasks. All user-defined crontab files are saved in the/var/spool/cron directory. The file name is the same as the user name.

 

User permission File:

File:

/Etc/cron. deny

Note:

Users listed in this file cannot use the crontab command.

File:

/Etc/cron. allow

Note:

Users listed in this file can use the crontab command

File:

/Var/spool/cron/

Note:

The directory where all user crontab files are stored, named after the user name

 

Meaning of the crontab file:

In the crontab file created by the user, each row represents a task, and each field in each row represents a setting. Its format is divided into six fields. The first five fields are time sets, the sixth part is the command segment to be executed. The format is as follows:

Minute hour day month week command

Where:

Minute: minute. It can be any integer from 0 to 59.

Hour: indicates the hour, which can be any integer from 0 to 23.

Day: indicates the date, which can be any integer from 1 to 31.

Month: represents the month, which can be any integer from 1 to 12.

Week: the day of the week. It can be any integer from 0 to 7. Here 0 or 7 represents Sunday.

Command: the command to be executed. It can be a system command or a script file compiled by yourself.

You can also use the following special characters in the preceding fields:

Asterisk (*): represents all possible values. For example, if the month field is an asterisk, this command is executed every month after the conditions of other fields are met.

Comma (,): values separated by commas (,) can be used to specify a list range, for example"

Middle bars (-): You can use the middle bars between Integers to represent an integer range. For example, "2-6" indicates "2, 3, 4, 5, 6"

Forward slash (/): You can use a forward slash to specify the interval of time. For example, "0-23/2" indicates that execution is performed every two hours. At the same time, the forward slash can be used with the star number, for example, */10. If it is used in the minute field, it indicates that the execution is performed every ten minutes.

 

II,Crond Service

Install crontab:

Yum install crontabs

Service operation instructions:

/Sbin/service crond start // start the service

/Sbin/service crond stop // close the service

/Sbin/service crond restart // restart the service

/Sbin/service crond reload // reload the configuration

View the crontab service status:

Service crond status

Start the crontab service manually:

Service crond start

Run the following command to check whether the crontab service is set to start at startup:

Ntsysv

Add boot auto start:

Chkconfig-level 35 crond on

 

III,Crontab command details

1.Command Format:

Crontab [-u user] file

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

2.Command function:

Through the crontab command, we can execute the specified system command or shell script at a fixed interval. The time interval can be any combination of minutes, hours, days, months, weeks, and above. This command includes non-permanent and periodic log analysis or data backup.

3.Command parameters:

-U user: used to set the crontab service for a user. For example, "-u ixdba" indicates to set the crontab service for the ixdba user. This parameter is generally run by the root user.

File: file is the name of the command file. It indicates that file is used as the task list file of crontab and is loaded into crontab. If this file is not specified in the command line, the crontab command accepts the commands typed on the standard input (keyboard) and loads them into the crontab.

-E: edit the contents of a user's crontab file. If no user is specified, the crontab file of the current user is edited.

-L: displays the contents of a user's crontab file. If no user is specified, the contents of the current user's crontab file are displayed.

-R: deletes the crontab file of a user from the/var/spool/cron directory. If no user is specified, the crontab file of the current user is deleted by default.

-I: A confirmation prompt is displayed when the user's crontab file is deleted.

4.Common Methods:

1). Create a New crontab file

 

Before submitting a crontab file to the cron process, you must set the environment variable EDITOR. The cron process determines which editor to use to edit the crontab file. 9 9% of UNIX and LINUX users use vi. If so, edit the. profile file in the $ HOME directory and add the following line to it:

EDITOR = vi; export EDITOR

Save and exit. Create Cron file, where Is the user name, for example, davecron. Add the following content to the file.

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

#15 minutes between 6 and 6 am

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

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

In the preceding example, the system outputs the current time to the console every 5 minutes. If the system crashes or hangs, you can see at the last displayed time when the system stops working. In some systems, tty1 is used to represent the console. You can modify the preceding example based on the actual situation. To submit the crontab file you just created, you can use the newly created file as a parameter of the cron command:

$ Crontab davecron

Now the file has been submitted to the cron process and will run every 5 minutes.

At the same time, a copy of the new file has been stored in the/var/spool/cron directory, and the file name is the user name (dave ).

2). List crontab Files

To list crontab files, you can use:

$ Crontab-l

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

You will see something similar to the above. You can use this method to back up the crontab file in the $ h o m e directory:

$ Crontab-l> $ HOME/mycron

In this way, once the crontab file is accidentally deleted, you can use the method described in the previous section to quickly restore it.

3). Edit the crontab file

If you want TO add, delete, or edit entries in the crontab file, and set the environment variable e d I to r to v I, you can use v I TO edit the crontab file, the corresponding command is:

$ Crontab-e

You can modify the crontab file and exit as you can edit any other file using v I. If some entries are modified or new entries are added, c r o n performs the necessary integrity check when saving the file. If a field contains a value out of the permitted range, it will prompt you.

We may add new entries when editing the crontab file. For example, add the following one:

# DT: delete core files, at 3.30am on, days of each month

30 3, 26 **/bin/find-name "core'-exec rm {}\;

Save and exit now. It is best to add a comment to each entry in the crontab file so that you can know its function and running time. More importantly, you can know which user's job this is.

Now let's use the previous crontab-l command to list all its information:

$ 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, days of each month

30 3, 26 **/bin/find-name "core'-exec rm {}\;

4). Delete the crontab file

To delete the crontab file, you can use:

$ Crontab-r

5). Restore the lost crontab file

If you accidentally delete the crontab file by mistake, if you have a backup in your $ h o m e directory, you can copy it to/var/spool/cron/ , Where Is the user name. If the copy cannot be completed due to permission issues, you can use:

$ Crontab

Where, Is the file name of your copy in the $ h o m e directory.

I suggest you save a copy of the file in your $ H O M E directory. I have had a similar experience and deleted the crontab file several times by mistake (because the r key is next to the right of the e key ). This is why it is recommended that you do not directly edit the crontab file in some system documents, but edit a copy of the file and resubmit the new file.

Some crontab variants are somewhat weird, so be careful when using the crontab command. If you omit any options, crontab may open an empty file or it looks like an empty file. Press delete to exit. Do not press Otherwise, the crontab file will be lost.

5.Use instance

Instance1:Execute command once every 1 minute

Command:

* *** Command

 

Instance2:3rd and 15th minutes per hour

Command:

3, 15 * command

 

Instance3:Run the command at 3rd and 15th minutes from eight o'clock A.M..

Command:

3, 15 8-11 *** command

 

Instance4:Run the command at 3rd and 15th minutes from eight o'clock A.M. to every two days.

Command:

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

 

Instance5:Run the command for 3rd and 15th minutes from eight o'clock A.M. to every Monday.

Command:

3, 15 8-11 ** 1 command

 

Instance6:Restart smb at every night

Command:

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

 

Instance7:Restart smb at on the 1st, 10th, and 22th of every month

Command:

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

 

Instance8:Restart smb at every Saturday and Sunday

Command:

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

 

Instance9:Restart smb every 30 minutes between to every day

Command:

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

 

Instance10:Restart smb at every Saturday.

Command:

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

 

Instance11:Restart smb every hour

Command:

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

 

Instance12:Restart smb every hour between PM and PM.

Command:

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

 

Instance13:Restart smb at every Monday to Wednesday on the 4th of each month

Command:

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

 

Instance14:Restart smb at on January 1, January 1

Command:

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

 

Instance15:Execute scripts in the/etc/cron. hourly directory every hour

Command:

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

Note:

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

 

IV,Precautions

1.Pay attention to environment variables

Sometimes we create a crontab, but this task cannot be automatically executed, but it is no problem to manually execute this task. This is generally caused by the absence of environment variables in the crontab file.

When defining multiple scheduling tasks in the crontab file, you need to pay special attention to 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, and the system will not load any environment variables when automatically executing the task scheduling. Therefore, you need to specify all the environment variables required for running the task in the crontab file, in this way, the system runs the task scheduling without any problems.

Do not assume that cron knows the required special environment. Therefore, make sure that all necessary paths and environment variables are provided in the shelll script, except for some automatically set global variables. Note the following three points:

1) write the global path when the script involves a file path;

2) When java or other environment variables are used for script execution, use the source command to introduce the environment variables, such:

Cat start_cbp.sh

#! /Bin/sh

Source/etc/profile

Export RUN_CONF =/home/d139/conf/platform/white/cbp_jboss.conf

/Usr/local/jboss-4.0.5/bin/run. sh-c PEM &

3) When you manually execute the script OK, but crontab does not run. In this case, you must boldly doubt that it is caused by environment variables and try to introduce environment variables in crontab to solve the problem. For example:

0 *****./etc/profile;/bin/sh/var/www/java/audit_no_count/bin/restart_audit.sh

 

2.Note: Clear the email logs of system users.

After each task is scheduled and executed, the system sends the task output information to the current system user by email. As a result, the log information is very large over time, it may affect the normal operation of the system. Therefore, it is very important to redirect each task.

For example, you can set the following format in the crontab file to ignore log output:

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

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

 

3.System-level task scheduling and user-level Task Scheduling

System-level task scheduling mainly performs system maintenance operations, and user-level task scheduling mainly completes user-defined tasks, user-level task scheduling can be completed by putting the user-level task scheduling into system-level Task Scheduling (this is not recommended), but this is not the case in turn, you can use "crontab-uroot-e" to set the task scheduling operation for the root user, or directly write the scheduling task to the/etc/crontab file. Note that, to define a scheduled system restart task, you must put the task in the/etc/crontab file, even if you create a scheduled system restart task under the root user, it is invalid.

4. Other considerations

The newly created cron job will not be executed immediately. It takes at least two minutes to execute it. If you restart cron, run the command immediately.

When the crontab suddenly fails, try/etc/init. d/crond restart to solve the problem. Or check the log to see whether a job has been executed or whether tail-f/var/log/cron has been reported.

Do not run crontab-r in disorder. It deletes your Crontab file from the Crontab directory (/var/spool/cron. All crontabs deleted from the user are gone.

In crontab, % indicates a line break. If you want to use it, you must escape \ %. For example, the commonly used date '+ % Y % m % d' will not be executed in crontab, change to date '+ \ % Y \ % m \ % d '.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.