Linux timed Task crontab command detailed

Source: Internet
Author: User
Tags delete key memory usage

The Linux system is controlled by the cron (Crond) system service. Linux systems have a lot of planned work on them, so this system service is started by default. In addition, because the user can set up scheduled tasks themselves, the Linux system also provides a command for the user to control scheduled tasks: the crontab command.

I. Introduction of Crond

Crond is a daemon that is used to periodically perform certain tasks or wait for certain events under Linux, similar to Scheduled tasks under Windows, when the operating system is installed, the Service tool is installed by default and the Crond process is started automatically. The Crond process periodically checks to see if there is a task to perform and automatically executes the task if there are tasks to perform.

The 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 cache data to hard disk, log cleanup, etc. In the/etc directory there is a crontab file, this is the System Task Scheduler configuration file.

The/etc/crontab file includes the following lines:





# Run-parts

* * * * * Root run-parts/etc/cron.hourly

7 * * * Root run-parts/etc/cron.daily

4 * * 0 root run-parts/etc/cron.weekly

4 1 * * Root run-parts/etc/cron.monthly

The first four rows are the environment variables that are used to configure the Crond task to run, the shell variable specifies which shell the system will use, this is bash, and the second line of the path variable specifies the path to the System execution command. The third line of the mailto variable specifies that Crond's task execution information will be emailed to the root user, and if the value of the mailto variable is null, the task execution information is not sent to the user, and the home variable in line fourth specifies the home directory to use when executing the command or script. The meaning of line sixth to Nineth is described in detail in the next section. There's not much to say here.

User Task scheduling: Users to perform regular work, such as user data backup, scheduled email reminders and so on. Users can use the Crontab tool to customize their own scheduled tasks. All user-defined crontab files are saved in the/var/spool/cron directory. Its file name is the same as the user name.

User Permissions File:




The users listed in this file are not allowed to use the crontab command




Users listed in this file are allowed to use the crontab command




directory where all user crontab files are stored, named by user name

What the crontab file means:

In the crontab file created by the user, each line represents a task, each field of each row represents a setting, its format is divided into six fields, the first five is the time setting segment, and the sixth paragraph is the command segment to execute, in the following format:

Minute hour day Month Week command


Minute: Represents minutes, which can be any integer from 0 to 59.

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

Day: Represents a date, which can be any integer from 1 to 31.

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

Week: Represents the day of the week, which can be any integer from 0 to 7, where 0 or 7 represents Sunday.

Command: The commands to execute can be either system commands or script files that you write yourself.

In each of these fields, you can also use the following special characters:

Asterisk (*): represents all possible values, such as the month field if it is an asterisk, the command action is executed monthly after the constraints of other fields are met.

Comma (,): You can specify a list range with a comma-separated value, for example, "1,2,5,7,8,9"

Middle Bar (-): An integer range can be represented by a middle bar between integers, such as "2-6" for "2,3,4,5,6"

Forward slash (/): You can specify the interval frequency of the time with a forward slash, such as "0-23/2", which is performed every two hours. A forward slash can be used with asterisks, such as */10, if used in the minute field, which means that it executes every 10 minutes.

Second, Crond service

Install Crontab:

Yum Install Crontabs

Service Operation Instructions:

/sbin/service Crond Start//Startup service

/sbin/service Crond stop//Shut down service

/sbin/service crond Restart//Restart service

/sbin/service Crond Reload//Reload Configuration

/sbin/service crond Status//Start service

To see if the Crontab service is set to boot, execute the command:


Add to boot auto start:

Chkconfig–level Crond on

Three, crontab command detailed

1. Command format:

crontab [-u user] File

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

2. Command function:

With the crontab command, we can execute specified system instructions or shell script scripts at a fixed interval of time. The units of the time interval can be any combination of minutes, hours, days, months, weeks, and more. This command is very useful for periodic log analysis or data backup.

3. Command parameters:

-u User: Used to set a user's crontab service, for example, "-u ixdba" means to set IXDBA user's crontab service, this parameter is usually run by the root user.

File:file is the name of the command file, which indicates that file is the Crontab task list and loaded into crontab. If this file is not specified on the command line, the crontab command will accept the commands typed on the standard input (keyboard) and load them into crontab.

-E: Edits the contents of a user's crontab file. If you do not specify a user, the crontab file for the current user is edited.

-L: Displays the contents of a user's crontab file, or displays the contents of the current user's crontab file if no user is specified.

-r: Deletes a user's crontab file from the/var/spool/cron directory and, if no user is specified, deletes the current user's crontab file by default.

-I: Give a confirmation prompt when deleting a user's crontab file.

4. Common methods:

1). Create a new crontab file

The first thing to do before considering submitting a crontab file to the cron process is to set the environment variable editor. The cron process depends on it to determine which editor to use to edit the crontab file. 9 9 of UNIX and Linux users use VI, and if you do, then you edit the $ home directory. Profile file in which to add such a line:

Editor=vi; Export EDITOR

Then save and exit. You might want to create a file named <user> Cron, where <user> is the user name, for example, Davecron. Add the following to the 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 that the previous 5 fields are separated by spaces.

In the example above, the system will output the current time to the console every 1 to 5 minutes. If the system crashes or hangs, you can see at what time the system stopped working at the last displayed time. In some systems, the use of tty1 to represent the console, according to the actual situation of the above example can be modified accordingly. In order to submit the crontab file you just created, you can use this newly created file as a parameter to the cron command:

$ crontab Davecron

Now that the file has been submitted to the Cron process, it will run every 1 5 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 user name (that is, Dave).

2). List crontab Files

In order 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 make a backup of the crontab file in the H O M e directory:

$ crontab-l > $HOME/mycron

This way, once the crontab file is accidentally deleted, it can be recovered quickly using the method described in the previous section.

3). Edit the Crontab file

If you want to add, delete, or edit an entry in the Crontab file, and the E D I to r environment variable is set to V I, then you can edit the crontab file with V I, and the corresponding command is:

$ crontab-e

You can modify the Crontab file and exit as if you were editing any other file using V I. If some entries are modified or a new entry is added, C R o N will perform the necessary integrity checks on the file when it is saved. If one of the fields has a value that exceeds the allowable range, it will prompt you.

When we edit the crontab file, we may not be adding a new entry. For example, add one of the following:

# Dt:delete Core Files,at 3.30am on 1,7,14,21,26,26 days of each month

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

Save and exit now. It is best to add a comment above each entry in the crontab file, so that you can know its function, run time, and, more importantly, what user's job it is.

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

$ crontab-l

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

# Dt:ech The date to the console every 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

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

4). Delete the crontab file

To delete a crontab file, you can use:

$ crontab-r

5). Recover the Lost crontab file

If you accidentally delete the crontab file, assuming you have a backup in your own $ H O M directory, you can copy it to/var/spool/cron/<username>, where <username> is the user name. If the copy cannot be completed due to a permissions issue, you can use:

$ crontab <filename>

Where,<filename> is the file name of your copy in the $ H O M e directory.

I recommend that you save a copy of the file in your own $ H O M directory. I have had a similar experience, several times accidentally deleted the crontab file (because the R key is close to the E key to the right). This is why some system documentation does not recommend editing the crontab file directly, but instead edits a copy of the file and then resubmit the new file.

Some variants of crontab are somewhat bizarre, so be careful when using the crontab command. If you omit any of the options, crontab may open an empty file, or it might look like an empty file. Then hit the delete key to exit, do not press <ctrl-d>, otherwise you will lose the crontab file.

5. Working with instances

Example 1: command is executed every 1 minutes
* * * * * command

Example 2:3rd and 15 minutes per hour of execution
3,15 * * * command

Example 3: Execution at 3rd and 15 minutes from 8 o'clock in the morning to 11.
3,15 8-11 * * command

Example 4:3rd and 15 minutes of every two-day 8 o'clock in the morning to 11-point execution
3,15 8-11 */2 * command

Example 5:3rd and 15 minutes of each Monday from 8 o'clock in the morning to 11.
3,15 8-11 * * 1 command

Example 6:21:30 restart of SMB per night
* * * * */ETC/INIT.D/SMB restart

Example 7:4:45 restart SMB per month for 1, 10, 22nd
4 1,10,22 * */ETC/INIT.D/SMB restart

Example 8:1:10 restart SMB per Saturday, Sunday
1 * * 6,0/ETC/INIT.D/SMB restart

Example 9: Restart SMB every 30 minutes from 18:00 to 23:00 daily
0,30 18-23 * * */ETC/INIT.D/SMB restart

Example 10: Every Saturday night at 11:00am restart SMB
0 * * 6/ETC/INIT.D/SMB restart

Example 11: Restart SMB every hour
* */1 * * * */ETC/INIT.D/SMB restart

Example 12: Restart SMB every hour from 11 o'clock to 7 in the morning
* 23-7/1 * * * */ETC/INIT.D/SMB restart

Example 13:4th per month with 11 points per Monday to Wednesday restart SMB
0 4 * MON-WED/ETC/INIT.D/SMB restart

Example 14:4-point restart of SMB on January 1
0 4 1 Jan */ETC/INIT.D/SMB restart

Example 15: Execution of scripts within/etc/cron.hourly directory per hour
* * * * * Root run-parts/etc/cron.hourly
Run-parts This parameter, if you remove this parameter, you can write a script name to run, not the directory name.

Iv. Precautions for use

Pay attention to the environment variable problem
Sometimes we create a crontab, but this task cannot be executed automatically, but it is not a problem to perform this task manually, which is usually caused by not configuring environment variables in the crontab file.

When defining multiple dispatch tasks in a crontab file, one of the issues that needs special attention is the setting of environment variables, because when we perform a task manually, it is done in the current shell environment, the program can certainly find the environment variable, and the system will not load any environment variables when it automatically executes the task schedule. Therefore, you need to specify all the environment variables that are required for the task to run in the crontab file, so that the system does not have a problem when it executes the Task Scheduler.

Don't assume that Cron knows the special circumstances you need, and it doesn't really know. So you have to make sure that you provide all the necessary path and environment variables in the shelll script, except for some auto-set global variables. So note the following 3 points:

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

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




Export run_conf=/home/d139/conf/platform/cbp/cbp_jboss.conf

/usr/local/jboss-4.0.5/bin/ MeV &

3) When the script is executed manually, but crontab is not executed. At this point, we must boldly suspect that environmental variables are the bane, and can try to directly introduce environmental variables in crontab to solve the problem. Such as:

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

Note Clean up the message log for system users
Each task is scheduled to execute, the system will send the task output information in the form of e-mail to the current system users, so the cumulative, log information will be very large, may affect the normal operation of the system, so it is important to redirect each task.

For example, you can set the following form in the crontab file, ignoring the 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 and then the standard error is redirected to standard output, and standard errors are redirected to/dev/null because the standard output has been redirected to/dev/null. This will solve the problem of log output.

System-level task scheduling and user-level task scheduling
System-level task scheduling is mainly to complete some maintenance operations of the system, user-level task scheduling is mainly to complete the user-defined tasks, you can put the user-level task scheduling to the system-level task scheduling to complete (not recommended), but in turn, the root user's task scheduling operation can be through the "crontab– Uroot–e "To set, you can also write the dispatch task directly to the/etc/crontab file, it is important to note that if you want to define a scheduled restart of the system task, you must put the task into the/etc/crontab file, even under the root user to create a The task of restarting the system regularly is also invalid.

Other precautions
The newly created cron job will not execute immediately, at least 2 minutes. If you restart Cron, it will be executed immediately.

When the crontab suddenly fails, you can try/etc/init.d/crond restart solve the problem. Or check the log to see if a job has execution/error tail-f/var/log/cron.

Don't run crontab-r. It removes the user's crontab file from the crontab directory (/var/spool/cron). All crontab of the user have been deleted.

In Crontab, the% has a special meaning, indicating the meaning of the line break. If you want to use the words must be escaped \%, such as the frequently used date ' +%y%m%d ' in the crontab will not be executed, should be replaced by the date ' +\%y\%m\%d '.


Use the Cron service to view the Cron service status with the server Crond status, if it is not started, service Crond start starts it, and the cron service is a timed execution service. You can add or edit tasks that need to be performed on a timed basis through the crontab command:

Crontab–u//Set a user's Cron service, which is usually required by the root user when executing this command
Crontab–l//list details of a user cron service
Crontab–r//Delete a user's cron service
Crontab–e//Edit a user's cron service
crontab filename//with filename as the crontab task list file and load

Service Crond Status View Cron service state, if not started, service Crond start starts it

The database needs to be automatically backed up at 0 points per day, so a scheduled task needs to be established. I chose to use crontab to add a timed task to execute the shell file under Linux. The shell file has a database backup command.


The function of the crontab command is to schedule execution of some commands at certain intervals.
Two View/etc/crontab File

Three Each line of the task in the file/etc/crontab is described in the following format:

Minute hour day Month DayOfWeek command

minute-integers from 0 to 59
hour-integers from 0 to 23
Day-an integer from 1 to 31 (must be a valid date for the specified month)
Month-an integer from 1 to 12 (or a month such as the Jan or Feb abbreviation)
DayOfWeek-integers from 0 to 7, 0 or 7 to describe Sunday (or as represented by sun or mon shorthand)
Command-commands to execute (commands that can be used as Ls/proc >>/tmp/proc or execute custom scripts)

Root indicates to run as root user
Run-parts means a folder followed by all the scripts under that folder

For each of these statements, the asterisk (*) represents all available values. For example, when referring to month, the command is executed monthly (subject to other restrictions).
The hyphen (-) between integers denotes an integer column, for example 1-4 means an integer 1,2,3,4
The specified value is separated by commas. Such as: 3,4,6,8 represents these four specified integers.
The symbol "/" specifies the stepping setting. "/<interger>" indicates a stepping value. such as the 0-59/2 definition is executed every two minutes. The step value can also be represented by an asterisk. such as */3 is used to run a specified task every three months running.

A comment line that begins with "#" is not executed.

If a cron task needs to be performed on a regular basis instead of by the hour, day, week, and month, you need to add the/ETC/CRON.D directory. All files and files in this directory are/etc/crontab in the same syntax, see the sample:

# Record the memory usage of the system every Monday
# at 3:30AM in the File/tmp/meminfo
3 * Mon cat/proc/meminfo >>/tmp/meminfo
# Run Custom Scrīpt the first day of every month at 4:10AM
4 1 * */root/scrīpts/

Users other than the root user can perform crontab configuration scheduled tasks. All user-defined crontab are stored under directory/var/spool/cron, and the task is executed as the creator. To create a crontab with a specific user, first log in as that user, execute command crontab-e, and the system initiates the editing crontab that is specified in visual or editor. The file content is the same as the/etc/crontab format. Examples are as follows:

0 3 * * */home/dbbackup/ Backup
0 4 * * */home/dbbackup/ Backup

Represents 3 points per day to perform/home/dbbackup/ backup,4 point execution/home/dbbackup/ Backup, if it is executed every five minutes can be changed to:

*/5 * * * */home/dbbackup/ Backup

When the changed crontab needs to be saved, the file is saved in the file/var/spool/cron/username as follows. The file name differs depending on the user name.

The Cron service checks for changes in/etc/crontab,/etc/cron.d/,/var/spool/cron files every minute. If a change is found, it is downloaded to the memory. Therefore, even if the crontab file changes, the program does not need to be restarted. The recommended custom task is added using the CRONTAB-E command, which restarts the crond process with the/etc/init.d/crond Restart command, and the official file says that it does not restart the process, but I am not able to run the task without restarting. Start do not know/etc/crontab file run-parts what meaning, direct command in accordance with the/etc/crontab format plus always can not run, later only know run-parts refers to the folder followed by.
Four Startup shutdown for Crontab services
Sbin/service Crond Start//Startup service
/sbin/service Crond stop//Shut down service
/sbin/service crond Restart//Restart service
/sbin/service Crond Reload//Reload Configuration

Linux timed Task crontab command detailed

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: 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.