Home  >  Article  >  Operation and Maintenance  >  What is the Linux user control scheduled task Crontab command and its detailed explanation

What is the Linux user control scheduled task Crontab command and its detailed explanation

伊谢尔伦
伊谢尔伦Original
2017-05-30 14:56:082062browse

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

1. Introduction to crond

crond is a daemon process used under Linux to periodically perform certain tasks or wait for processing certain events. It is similar to scheduled tasks under Windows. When installed After completing the operating system, this service tool will be installed by default, and the crond process will be automatically started. The crond process will regularly check whether there are tasks to be executed every minute. If there are tasks to be executed, the task will be automatically executed.

Task scheduling under Linux is divided into two categories, system task scheduling and user task scheduling.

System task scheduling: The work that the system performs 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.

/etc/crontab file includes the following lines:

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


The first four lines are used to configure the environment variables for crond task running. The first line of SHELL variable specifies the system to use Which shell, here is bash, the PATH variable in the second line specifies the path for the system to execute the command, and the MAILTO variable in the third line specifies the crond task execution information that will be sent to the root user via email. If the value of the MAILTO variable is empty, then Indicates that task execution information is not sent to the user. The HOME variable in the fourth line specifies the home directory used when executing commands or scripts. The meanings represented by lines six to nine will be described in detail in the next section. Not much to say here.

User task scheduling: tasks that users need to perform regularly, such as user data backup, regular email reminders, etc. Users can use the crontab tool to customize their own scheduled tasks. All user-defined crontab files are stored in the /var/spool/cron directory. Its file name is consistent with the user name.

User permissions file:

File:

/etc/cron.deny

Description:

Listed in this file Users are not allowed to use the crontab command

File:

/etc/cron.allow

Description:

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

File:

/var/spool/cron/

Description:

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

The meaning of the crontab file:

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

minute hour day month week command

where:

minute : represents the minute, which can be any integer from 0 to 59.

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

day: represents the date, which can be any integer from 1 to 31.

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

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

command: The command to be executed can be a system command or a script file written by yourself.

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

Asterisk (*): represents all possible values, for example, if the month field is an asterisk , it means that the command operation will be executed every month after the constraints of other fields are met.

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

Middle bar (-): You can use a dash between integers to represent an integer range, for example, "2-6" means "2,3,4,5,6"

Forward slash (/): You can use a forward slash to specify Time interval frequency, for example "0-23/2" means execution every two hours. At the same time, forward slashes can be used together with asterisks, such as */10. If used in the minute field, it means that it will be executed every ten minutes.

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

/sbin/service crond status //Start the service


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

ntsysv

Add automatic startup at boot:

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 commands or shell scripts at fixed intervals. The unit of time interval can be minutes, hours, days, months, weeks, or any combination of above. This command is very suitable for periodic log analysis or data backup and other tasks.

3. Command parameters:

-u user: used to set the crontab service of a certain user. For example, "-u ixdba" means setting the crontab service of the ixdba user. This parameter is generally run by the root user.

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

-e: Edit the contents of a user's crontab file. If no user is specified, it means editing the crontab file of the current user.

-l: Display the crontab file contents of a certain user. If the user is not specified, it means displaying the crontab file contents of the current user.

-r: Delete a user's crontab file from the /var/spool/cron directory. If no user is specified, the current user's crontab file will be deleted by default.

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

4. Commonly used methods:

1). Create a new crontab file

Before considering submitting a crontab file to the cron process, the first thing 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. If you do the same, then edit the . profile file in the $HOME directory and add this line to it:

EDITOR=vi; export EDITOR

Then save and exit. Consider creating a file called cron, where is the username, for example, davecron. Add the following content 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, the last time displayed will tell you at a glance when the system stopped working. In some systems, tty1 is used to represent the console, and the above example can be modified accordingly according to the actual situation. In order to submit the crontab file you just created, you can pass this newly created file as a parameter of the cron command:

$ crontab davecron

Now that the file has been submitted to the cron process, it will be used every Runs 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 user name (ie 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 content 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

In this way, if you accidentally delete the crontab file, You can quickly recover using the method described in the previous section.

3). Edit the crontab file

If you want to add, delete or edit entries in the crontab file, and the E D I TO R environment variable is set to vi, you can use vi to edit the crontab file, the corresponding command is:

$ crontab -e

You can modify the crontab file and exit just like using vi to edit any other file. If some entries are modified or new entries are added, cron will perform the necessary integrity checks on the file when it is saved. If one of the fields has a value outside the allowed range, it will prompt you.

When we edit the crontab file, we may add new entries. For example, add the following:

# 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 is best to add a comment above each entry in the crontab file, In this way, you can know its function, running time, and more importantly, which user's job it is.

Now let us use the crontab -l command mentioned earlier to list all its information. :

$ crontab -l

# (crontab 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

To delete the crontab file, you can use:

$ crontab -r

5). Restore the lost crontab file

If you accidentally delete the crontab file, assuming you still have a backup in your $H O M E directory, you can copy it to /var/spool/cron/, where is username. If the copy cannot be completed due to permission issues, you can use:

$ crontab

where is the name of the file you copied in the $H O M E directory.

I recommend that you save a copy of this file in your $H O M E directory. I had a similar experience and accidentally deleted the crontab file several times (because the r key is immediately to the right of the e key). This is why some system documentation recommends not to edit the crontab file directly, but to edit a copy of the file and then resubmit the new file.

Some crontab variations are a little weird, so be careful when using the crontab command. If any options are omitted, crontab may open an empty file, or appear to be an empty file. At this time, hit the delete key to exit. Do not press , otherwise you will lose the crontab file.

5. Usage example

Example 1: Execute command
command every 1 minute:
* * * * * command

Instance 2: The 3rd and 3rd times every hour Execute
command in 15 minutes:
3,15 * * * * command

Example 3: Execute
command in the 3rd and 15th minutes from 8 am to 11 am :
3,15 8-11 * * * command

Example 4: Execute the
command at the 3rd and 15th minutes from 8 am to 11 am every two days:
3,15 8-11 */2 * * command

Example 5: Execute the
command at the 3rd and 15th minutes from 8 am to 11 am every Monday :
3,15 8-11 * * 1 command

Instance 6: Restart smb at 21:30 every night
Command:
30 21 * * * /etc/ init.d/smb restart


Instance 7: Restart smb at 4:45 on the 1st, 10th, and 22nd of every month
Command:
45 4 1,10,22 * * / etc/init.d/smb restart


Instance 8: Restart smb at 1:10 every Saturday and Sunday
Command:
10 1 * * 6,0 /etc/ init.d/smb restart


Instance 9: Restart smb every 30 minutes between 18:00 and 23:00 every day
Command:
0,30 18-23 * * * /etc/init.d/smb restart


Instance 10: Restart smb every Saturday at 11:00 pm
Command:
0 23 * * 6 /etc/init. d/smb restart


Example 11: Restart smb every hour
Command:
* */1 * * * /etc/init.d/smb restart


Example 12: Restart smb every hour between 11pm and 7am
Command:
* 23-7/1 * * * /etc/init.d/smb restart

Instance 13: Restart smb on the 4th of every month and every Monday to Wednesday at 11 o'clock
Command:
0 11 4 * mon-wed /etc/init.d/smb restart

Example 14: Restart smb at 4 o'clock on January 1st
Command:
0 4 1 jan * /etc/init.d/smb restart


Example 15: Execute the script in the /etc/cron.hourly directory every hour
Command:
01 * * * * root run-parts /etc/cron.hourly
Instructions:
run -parts parameter. If you remove this parameter, you can write the name of a script to be run instead of the directory name.


4. Precautions for use

Note Environment variable problem
Sometimes we create a crontab, but the task cannot be executed automatically, but there is no problem when executing the task manually. This situation is generally caused by the fact that the environment variable is not configured in the crontab file.

When defining multiple scheduling tasks in a crontab file, one issue that requires 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. When the system automatically performs task scheduling, it will not load any environment variables. Therefore, you need to specify all the environment variables required for task running in the crontab file. In this way, there will be no problem when the system performs task scheduling. .

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

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

2) When the script execution requires java or other environment variables, introduce the environment variables through the source command. , such as:

cat start_cbp.sh

#!/bin/sh

source /etc/profile

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

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

3) When executing the script manually, it is OK, but When crontab is not executed. At this time, you must boldly suspect that environment variables are to blame, and you can try to directly 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

Pay attention to clearing the system user’s mail log
After each task is scheduled to be executed, the system will send the task output information to the current system user via email. Over time, the log information will be very large and may affect the normal operation of the system. Therefore, each task will be It's very important to handle redirects.

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

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

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

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. User-level task scheduling can be placed Go to system-level task scheduling to complete (this is not recommended), but the reverse does not work. The root user's task scheduling operation can be set through "crontab –uroot –e", or the scheduled task can be written directly to /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 will be invalid.

Other Notes
The newly created cron job will not be executed immediately, but will take at least 2 minutes to execute. If cron is restarted, 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 has been executed/reported an error tail -f /var/log/cron.

Never run crontab -r randomly. It deletes the user's Crontab files from the Crontab directory (/var/spool/cron). All crontabs of this user are gone after deletion.

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

The above is the detailed content of What is the Linux user control scheduled task Crontab command and its detailed explanation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn