The previous day I learned that the AT command is a routine scheduled task that runs only once, and the Linux system is controlled by the cron (Crond) system service. There is already a lot of planned work on Linux, so the system service starts by default. In addition, because users can set scheduled tasks by themselves, Linux also provides the command crontab command for users to control scheduled tasks.

I. Introduction to Crond

Crond is a daemon in Linux that periodically performs a task or waits for an event to be processed. Similar to scheduled tasks in Windows, crond is installed by default after the operating system is installed. The Crond process automatically starts. If there is a task to be executed, it is automatically executed.

Task scheduling in Linux is divided into two types: system task scheduling and user task scheduling.

System task scheduling: Periodic tasks to be performed by the system, such as writing cached data to hard disks and clearing logs. There is a crontab file in the /etc directory, which is the configuration file of 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 ~]#Copy the code

The first four lines are used to configure the environment variables to run the Crond task. The first line of the SHELL variable specifies which SHELL the system will use, in this case bash, and the second line of the PATH variable specifies where the system will execute the command. The third line of the MAILTO variable specifies that the task execution information of Crond will be emailed to the root user. If the value of the MAILTO variable is empty, the task execution information will not be sent to the user. The fourth line of the HOME variable specifies the HOME directory to use when executing a command or script. The meaning of lines 6 through 9 is described in detail in the next section. I won’t say more here.

User task scheduling: tasks to be performed periodically by users, such as user data backup and periodic email notification. Users can use the Crontab tool to customize their 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

Description:

Users listed in this file 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:

Directory for storing crontab files of all users, named with the user name

Crontab file meaning:

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

minute   hour   day   month   week   command

Among them:

“Minute” : indicates the minute. The value can be any integer from 0 to 59.

Hour: indicates the hour. The value can be any integer from 0 to 23.

Day: indicates the date. The value 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. The value can be any integer between 0 and 7, where 0 or 7 represents Sunday.

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

 

You can also use the following special characters in each of the above fields:

Asterisk (*) : indicates all possible values. For example, the asterisk (*) in the month field indicates that the command will be executed every month after all restrictions on other fields are met.

Comma (,) : comma-separated values specify a list range, for example, “1,2,5,7,8,9”

Middle bar (-) : A range of integers can be represented by a middle bar between integers, for example “2-6” for “2,3,4,5,6”

Slash (/) : You can use a slash to specify the interval frequency. For example, 0-23/2 indicates that the interval is executed every two hours. A forward slash can be used with an asterisk, for example, */10. If it is used in the minute field, the command is executed every 10 minutes.

Crond service

Install the crontab:

yum install crontabs

Service operation instructions:

/sbin/service crond start // Starts the service

/sbin/service crond stop // Stops the service

/sbin/service crond restart // Restart the service

/sbin/service crond reload // Reloads the configuration

Check the crontab service status:

service crond status

Manually start the crontab service:

service crond start

Run the following command to check whether the crontab service is enabled upon startup:

ntsysv

Add automatic startup after startup:

Chkconfig – level 35 crond on

Explain the crontab command

1. Command format:

crontab [-u user] file

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

2. Run the following command:

With the crontab command, you can execute specified system commands or shell scripts at fixed intervals. The unit of time interval can be any combination of minutes, hours, days, months, weeks or more. This command is not used for periodic log analysis or data backup.

3. Command parameters:

-u user: indicates the crontab service of a user. For example, -u ixdba indicates the crontab service of user IXdba. This parameter is usually run by the root user.

File: File is the name of the command file, indicating that file is used as the crontab task list file and crontab is loaded. 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: edits the crontab file of a user. If no user is specified, the crontab file of the current user is edited.

-l: displays the crontab file of a user. If no user is specified, the crontab file of the current user is 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: prompts confirmation when deleting the crontab file of the user.

4. Common methods:

1). Create a new crontab file

Before you consider committing a crontab file to the Cron process, one of the first things you need to do is set the environment variable EDITOR. The Cron process uses this to determine which editor to use to edit the crontab file. 9.9% of UNIX and LINUX users use vi. If that’s you, edit the.profile file in the $HOME directory and add a line like this:

EDITOR=vi; export EDITOR

Then save and exit. Create a file called <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 the first five fields are separated by Spaces.

In the example above, the system prints 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. On some systems, the console is referred to as TTy1, and the above example can be modified accordingly. To submit the crontab file you just created, use the newly created file as an argument to the cron command:

     $ crontab davecron

Now that the file is committed to the Cron process, it will run every 15 minutes.

Meanwhile, a copy of the newly created file has been placed in the /var/spool/cron directory, with the filename being the user name (i.e., Dave).

2). List crontab files

To list crontab files, use:

     $ crontab -l

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

You’ll see something similar to the above. $H O M E $H O M E $H O M E

     $ crontab -l > $HOME/mycron

This way, if you accidentally delete a crontab file, you can quickly recover it using the method described in the next section.

3). Edit crontab file

If you want TO add, delete, or edit items in the crontab file and the E D I TO R environment variable is set TO v I, you can edit the crontab file with v I. The corresponding command is:

     $ crontab -e

You can modify the crontab file as you would any other file with vi and exit. If some entries are modified or new entries are added, c R O N performs the necessary integrity checks on the file when it is saved. It will alert you if one of the fields has a value that is out of the allowed range.

When we edit the crontab file, we might 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 a good idea to add a comment above 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 we talked about 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 crontab files

To delete the crontab file, use:

    $ crontab -r

5). Restore the lost crontab file

If you delete the crontab file by mistake, you can copy it to /var/spool/cron/<username>, assuming you have a backup file in your $H O M E directory. If the copy cannot be completed due to permissions, you can use:

     $ crontab <filename>

Where <filename> is the filename of your copy 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, deleting crontab files by mistake several times (because the R key was right next to the E key). This is why some system documentation recommends not editing the crontab file directly, but instead editing a copy of the file and resubmitting the new file.

Some crontab variants are a bit weird, so be careful when using the crontab command. If any options are missing, crontab may open an empty file or appear to be empty. Press delete to exit, do not press < Ctrl-d > or you will lose the crontab file.

5. Using the instance

Example 1: Run command every minute

Command:

* * * * * command

 

Example 2: execution at the 3rd and 15th minutes of every hour

Command:

3,15 * * * * command

 

Example 3: Execute at the 3rd and 15th minutes between 8 a.m. and 11 a.m

Command:

3,15 8-11 * * * command

 

Example 4: The 3rd and 15th minutes are executed every other day from 8 a.m. to 11 a.m

Command:

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

 

Example 5: The 3rd and 15th minutes are executed every Monday from 8 a.m. to 11 a.m

Command:

3,15 8-11 * * 1 command

 

Example 6: Restart the SMB at 21:30 every night

Command:

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

 

Example 7: SMB restarts at 4:45 on the first, 10th, and 22nd of each month

Command:

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

 

Example 8: Restart the SMB at 1:10 every Saturday and Sunday

Command:

10 1 * * 6 0 /etc/init.d/ SMB restart

 

Example 9: Restart the SMB every 30 minutes between 18:00-23:00 every day

Command:

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

 

Example 10: Restart the SMB every Saturday at 11:00pm

Command:

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

 

Example 11: Restart the SMB every hour

Command:

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

 

Example 12: Restart the SMB every hour between 11 p.m. and 7 a.m

Command:

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

 

Example 13: Restart the SMB on the 4th of each month and Monday through Wednesday at 11am

Command:

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

 

Example 14: Restart the SMB at 4:00 a.m. on January 1

Command:

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

Example 15: The hourly scripts in the /etc/cron.hourly directory are executed

Command:

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

Description:

The run-parts argument, if removed, can be followed by the name of the script to be run instead of the directory name

Iv. Precautions for use

1. Pay attention to environment variables

Sometimes a crontab is created, but the task cannot be executed automatically, and the task can be executed manually with no problem. This is usually caused by the fact that no environment variables are configured in the crontab file.

In crontab files define multiple scheduling tasks, need to pay special attention to a problem is the environment variable Settings, because we manually perform a task, is under the environment of the current shell, application environment variables can be found, of course, the system automatically, when performing a task scheduling is not loaded any environment variables, therefore, You need to specify all the environment variables required to run the task in the crontab file, so that the system can execute the task scheduling without any problems.

Don’t assume that Cron knows about the particular environment required, it doesn’t. So make sure you provide all the necessary paths and environment variables in your shelll script, except for some automatically set global variables. So here are three things to note:

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

2) When Java or other environment variables are needed for script execution, use the source command to introduce environment variables, 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. The sh – mev & c

3) When the script OK is executed manually, but the crontab does not execute. You must suspect that environment variables are to blame and try to fix the problem by introducing environment variables directly in crontab. Such as:

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

2. Clear the mail logs of system users

After each task is scheduled, the system sends the task output information to the current system user in the form of an email. In this case, the accumulated log information is very large and may affect the normal running of the system. Therefore, it is 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 redirects the standard output to /dev/null and then the standard error to the standard output. Since the standard output has been redirected to /dev/null, the standard error will also be redirected to /dev/null, and the log output problem will be solved.

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

System-level task scheduling mainly completes system maintenance operations, and user-level task scheduling mainly completes user-defined tasks. You can transfer user-level task scheduling to system-level task scheduling (not recommended), but the reverse is not possible. You can run the crontab -uroot -e command to schedule tasks for the root user, or directly write the task to the /etc/crontab file. Note that if you want to define a task for periodically restarting the system, you must put the task in the /etc/crontab file. Even creating a timed restart task as user root is invalid.

4. Other precautions

A newly created Cron job will not be executed immediately but will be executed at least two minutes later. If cron is restarted, it is executed immediately.

If the crontab fails suddenly, run the /etc/init.d/crond restart command to resolve the problem. Tail -f /var/log/cron Check whether a job is executed/an error occurs.

Don’t run crontab -r randomly. It removes the user’s Crontab file from the Crontab directory (/var/spool/cron). All crontabs that deleted the user are gone.

In crontab, % has a special meaning, meaning a line break. If you want to use crontab, you must escape \%, for example, date ‘+%Y%m%d’ will not be executed in crontab, you should change it to date ‘+%Y%m%d’.