Design of a scheduled task using crontab in CentOS

Source: Internet
Author: User

Design of a scheduled task using crontab in CentOS

The at command is for a task that only runs once and runs cyclically scheduled tasks. In linux, cron (crond) is the system service. The Linux system has a lot of planned work, so this system service is started by default. In addition, because you can also set scheduled tasks, Linux also provides the crontab command for you to control scheduled tasks.

1. 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 **** rootrun-parts/etc/cron. hourly

247 * rootrun-parts/etc/cron. daily

224 ** 0rootrun-parts/etc/cron. weekly

4241 ** rootrun-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:

Minutehourdaymonthweekcommand

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:

Yuminstallcrontabs

Service operation instructions:

/Sbin/servicecrondstart // start the service

/Sbin/servicecrondstop // close the service

/Sbin/servicecrondrestart // restart the service

/Sbin/servicecrondreload // reload the configuration

View the crontab service status:

Servicecrondstatus

Start the crontab service manually:

Servicecrondstart

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

Ntsysv

Add boot auto start:

Chkconfig-level35crondon

Iii. crontab command details

1. Command Format:

Crontab [-uuser] file

Crontab [-uuser] [-e |-l |-r]

2. command functions:

Through the crontab command, we can execute the specified system command or shellscript 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:

-Uuser: used to set the crontab service for a user. For example, "-uixdba" indicates to set the crontab service for ixdba users. 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. 99% 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; exportEDITOR

Save and exit. Create a file named <user> cron, where <user> is the user name, for example, davecron. Add the following content to the file.

# (Putyourowninitialshere) echothedatetotheconsoleevery

# 15minutesbetween6pmand6am

,-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 15 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:

$ Crontabdavecron

Now the file has been submitted to the cron process and will run every 15 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 $ HOME 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 EDITOR environment variable 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 as if you were using vi to edit any other files. If some entries are modified or new entries are added, cron will perform necessary integrity checks 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: deletecorefiles, at3.30amon1, 7,14, 21,26, 26 daysofeachmonth

3031,7, 14,21, 26 **/bin/find-name "core'-execrm {}\;

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

# (CrondaveinstalledonTueMay413: 07:431999)

# DT: echthedatetotheconsoleevery30minites

,-06 ***/bin/echo 'date'>/dev/tty1

# DT: deletecorefiles, at3.30amon1, 7,14, 21,26, 26 daysofeachmonth

3031,7, 14,21, 26 **/bin/find-name "core'-execrm {}\;

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 $ HOME directory, you can copy it to/var/spool/cron/<username>, <username> indicates the user name. If the copy cannot be completed due to permission issues, you can use:

$ Crontab <filename>

<Filename> indicates the file name of the copy in the $ HOME directory.

We recommend that you save a copy of the file in your $ HOME 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 <Ctrl-D>. Otherwise, the crontab file will be lost.

5. Use instances

Instance 1: Execute command once every minute

Command:

* *** Command

Instance 2: 3rd and 15th minutes per hour

Command:

3, 15 * command

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

Command:

3,158-11 *** command

Instance 4: runs every two days, from eight o'clock A.M. to, at 3rd and 15th minutes.

Command:

3,158-11 */2 ** command

Instance 5: run the task at 3rd and 15th minutes from eight o'clock A.M. to every Monday.

Command:

3,158-11 ** 1 command

Instance 6: restart smb at every night

Command:

3021 ***/etc/init. d/smbrestart

Instance 7: restart smb at on the 1st, 10th, and 22th of every month

Command:

4541,10, 22 **/etc/init. d/smbrestart

Instance 8: restarts smb at every Saturday and Sunday.

Command:

101 ** 6, 0/etc/init. d/smbrestart

Instance 9: restart smb every 30 minutes from to every day

Command:

0, 3018-23 ***/etc/init. d/smbrestart

Instance 10: restart smb at every Saturday.

Command:

023 ** 6/etc/init. d/smbrestart

Instance 11: restart smb every hour

Command:

**/1 ***/etc/init. d/smbrestart

Instance 12: restart smb every hour between PM and PM.

Command:

* 23-7/1 ***/etc/init. d/smbrestart

Instance 13: restart smb at from Monday to Wednesday on the 4th of each month

Command:

0114 * mon-wed/etc/init. d/smbrestart

Instance 14: restart smb at on January 1, January 1

Command:

041jan */etc/init. d/smbrestart

Example 15: execute scripts in the/etc/cron. hourly directory every hour.

Command:

01 ***** rootrun-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:

Catstart_cbp.sh

#! /Bin/sh

Source/etc/profile

ExportRUN_CONF =/home/d139/conf/platform/white/cbp_jboss.conf

/Usr/local/jboss-4.0.5/bin/run. sh-CMW &

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. Clear 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/apachectlrestart>/dev/null2> & 1

"/Dev/null2> & 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 cronjob 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/crondrestart 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 '.

Related Article

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.