Detailed explanation of linux system timing task command

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


Install


yum -y install vixie-cron
yum -y install crontabs


1. Introduction


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


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


The /etc/crontab file contains 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 SHELL variable specifies which shell the system will use, here is bash, the second line PATH variable specifies the path of the system to execute commands, and the third line MAILTO variable specifies the crond task execution The information will be sent to the root user by email. If the value of the MAILTO variable is empty, it means that no task execution information will be sent to the user. The HOME variable on the fourth line specifies the home directory used when executing commands or scripts. The meaning of the sixth to ninth lines will be described in detail in the next subsection. Not much to say here.


User task scheduling: The tasks that users need to perform on a regular basis, 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 the same as the user name.


User Rights File:


File:


/etc/cron.deny


Description:


Users listed in this file are not allowed to use crontab commands


File :


/etc/cron.allow


Description:


Users listed in this file are allowed to use crontab commands


File :


/var /spool/cron/


Description:





The directory where all user crontab files are stored, and the meaning of the crontab file named after the user name : 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 paragraphs are time setting paragraphs, and the sixth paragraph is the


command paragraph to be executed . . 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: 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, which can be a system command or a script file written by yourself. In 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 (,): A list range can be specified with comma-separated values, for example, "1,2,5,7,8,9" Bars (-): A bar between integers can be used to indicate a range of integers , for example "2-6" means "2,3,4,5,6" Forward slash (/): You can specify the interval frequency of time with a forward slash, for example "0-23/2" means to execute every two hours once. At the same time, forward slashes can be used together with asterisks, such as */10, if used in the minute field, it means to execute every ten minutes. 2. crond service







































Install crontab:


yum install crontabs


Service Instructions:


/sbin/service crond start //Start service


/sbin/service crond stop //Close service


/sbin/service crond restart //Restart service


/sbin/service crond reload //Reload Enter 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 is


added to start automatically at boot:


chkconfig –level 35 crond on


3. Detailed explanation of the 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 the specified system command or shell script script at a fixed interval. The unit of time interval can be minutes, hours, days, months, weeks, and any combination of the above. This command is ideal for periodic log analysis or data backup.


3. Command parameters:


-u user: used to set the crontab service of a user, for example, "-u ixdba" means to set 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, indicating 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 to edit the current user's crontab file.


-l: Display the content of a user's crontab file. If no user is specified, it means that the content of the current user's crontab file is displayed.


-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: Prompt for confirmation when deleting a user's crontab file.


4. Common methods:


1). Create a new crontab file


Before considering submitting a crontab file to the cron process, one of the first things 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, then edit the .profile file in your $HOME directory and add this line to it:


EDITOR=vi; export EDITOR


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


$ crontab davecron


Now that the file has been submitted to the cron process, it will run 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 username (ie dave).


2). List crontab files


To list crontab files, 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 $HOME directory:


$ crontab -l > $HOME/mycron In


this way, if you accidentally delete the crontab file by mistake, you can quickly restore it using the method described in the previous section.


3). Editing the crontab file


If you want to add, delete or edit entries in the crontab file, and the EDITOR environment variable is set to vi, then you can use vi to edit the crontab file. The corresponding command is:


$ crontab -e


modifies the crontab file like any other file with vi and exits. If some entries are modified or new entries are added, cron performs the necessary integrity checks on the file when saving it. It will alert you if one of these fields has a value that is out of the allowed range.


As 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's a good idea to put a comment above each entry in the crontab file so you know what it does, when it runs, and most importantly, know Which user's job is this.


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). Removing the crontab file


To remove the crontab file, use:


$ crontab -r


5). Restoring a lost crontab file


If you accidentally delete a crontab file, assuming you have a backup in your $HOME directory, you can copy it to /var/spool/cron/<username>, where <username> is Username. If the copy cannot be done due to permission issues, you can use:


$ crontab <filename>


where <filename> is the filename of your copy in your $HOME directory.


I suggest you keep a copy of this file in your $HOME directory I have had a similar experience and deleted the crontab file by mistake several times (because the r key is immediately to the right of the e key). This is why some system documentation recommends not editing the crontab file directly, but editing the file's Make a copy, then re-commit the new file.


Some crontab variants are a bit weird, so be careful when using the crontab command. If any options are left out, crontab may open an empty file, or appear to be an empty file. At this time, press the delete key to exit, do not press <Ctrl-D>, otherwise you will lose the crontab file.


5.


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


3 and 15 minutes to execute the
command :
3,15 * * * * command


instance 3: Execute at the 3rd and 15th minutes from 8 am to 11 am
Command :
3,15 8-11 * * * command


instance 4: every two days from 8 am to 11 am Execute the
command 11:
3,15 8-11 */2 * * command


Example 5: Execute the
command :
3, 15 8-11 * * 1 command


instance 6: restart smb
command at 21:30 every night:
30 21 * * * /etc/init.d/smb restart




instance 7: 4:45 on the 1st, 10th, and 22nd of each month Restart smb
command:
45 4 1,10,22 * * /etc/init.d/smb restart




Example 8: Every Saturday and Sunday at 1:10 restart smb
command:
10 1 * * 6,0 /etc/init .d/smb restart




instance 9: every 30 minutes between 18:00 and 23:00 restart smb
command:
0,30 18-23 * * * /etc/init.d/smb restart




instance 10: every Saturday 11:00pm restart smb
command:
0 23 * * 6 /etc/init.d/smb restart




instance 11: restart smb
command every hour:
* */1 * * * /etc/init.d/smb restart




instance 12: 11pm to 7am Between, restart the smb
command every hour :
* 23-7/1 * * * /etc/init.d/smb restart


instance 13: every 4th of every month and every Monday to Wednesday at 11:00 to restart the smb
command:
0 11 4 * mon-wed /etc/init.d/smb restart Example 14: Restart the smb command


at 4:00 on the 1st of January : 0 4 1 jan * /etc/init.d/smb restart Example 15: Execute every hour / Script in the etc/cron.hourly directory Command : 01 * * * * root run-parts /etc/cron.hourly Description: run-parts is the parameter, if you remove this parameter, you can write the one to run later Script name, not directory name 4. Precautions for use Pay attention to the problem of environment variables Sometimes we create a crontab, but this task cannot be executed automatically, but there is no problem in executing this task manually. This situation is generally due to the crontab file. Caused by no environment variables configured in.






















When defining multiple scheduling tasks in the crontab file, one issue that needs 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, while the system When automatically executing task scheduling, no environment variables will be loaded. Therefore, it is necessary to specify all the environment variables required for task running in the crontab file, so that there is no problem when the system executes task scheduling.


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


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


2) When the script execution uses java or other environment variables, import 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 manually executing the script OK , but when crontab is not executed. At this time, you must boldly suspect that the environment variable is to blame, and you can try to directly introduce the environment variable in crontab to solve the problem. Such as:


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


Pay attention to cleaning up the mail log of system users
After each task is scheduled and executed, the system will send the task output information to the current system user in the form of e-mail. In this way, the log information will be very large over time, which may affect the normal operation of the system. Therefore, each task is redirected. Handling is very important.


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" Redirect standard output 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 That's it.


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, which can be done by placing user-level task scheduling in system-level task scheduling (not It is recommended to do this), but the reverse is not possible. The task scheduling operation of the root user can be set through "crontab -uroot -e", or the scheduling task can be directly written to the /etc/crontab file. It should be noted that if you want to 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 is invalid.


Other considerations
The newly created cron job will not be executed immediately, and it will take at least 2 minutes to execute. If you restart cron, 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 is executed/errored tail -f /var/log/cron.


Never run crontab -r indiscriminately. It removes the user's Crontab file from the Crontab directory (/var/spool/cron). Deleted all crontabs for that user and it's gone.


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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728012&siteId=291194637