Linux common commands: crontab command


  I learned the day before that the at command is for tasks that run only once, routinely scheduled tasks that run cyclically, and the linux system is controlled by the system service cron (crond). 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 the command :crontab command for users to control scheduled tasks.

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 the operating system is installed, this service tool will be installed by default and will start automatically. The crond process, the crond process will periodically check whether there is a task to be executed every minute, and 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:  

[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 ~]#

 

  The first four lines are used to configure the environment variables for running the crond task. The first line SHELL variable specifies which shell the system will use, here is bash, the second line PATH variable specifies the path for the system to execute commands, and the third line MAILTO variable specifies The task execution information of crond will be sent to the root user by email. If the value of the MAILTO variable is empty, it means that the task execution information will not be sent to the user. The HOME variable in the fourth line specifies the home page used when executing the command or script. content. 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 permissions file:

document:

/etc/cron.deny

illustrate:

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

document:

/etc/cron.allow

illustrate:

Users listed in this file are allowed to use crontab commands

document:

/ var / spool / cron /

illustrate:

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

  Meaning of 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 paragraphs are time setting paragraphs, and the sixth paragraph is The command segment to be executed, in the following format:

minute   hour   day   month   week   command

in:

minute: Indicates the minute, which 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: 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 each of the above fields, the following special characters can also be used:

  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"

  Middle bar (-): You can use a middle bar between integers to represent 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. 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 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 configuration

View crontab service status:

service crond status

Start the crontab service manually:

service crond start

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

  ntsysv

Add the boot to start automatically:

  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 regular intervals. 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 method:

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, and 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, once the crontab file is accidentally deleted, it can be quickly restored using the method described in the previous section.

3). Edit 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

  The crontab file can be modified like any other file with vi and exit. If some entries are modified or new entries are added, the cron will perform the necessary integrity checks on the file when it is saved. 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 one:

# 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 on top of 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 mentioned 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 the crontab file

  To delete the crontab file, you can use:

    $ crontab -r

5). Recover lost crontab file

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

    $ crontab <filename>

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

  I recommend that you keep a copy of this file in your $HOME directory. I 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 a copy of the file and resubmitting the new file.

  Some crontab variants are a little weird, so be extra 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, hit the delete key to exit, do not press <Ctrl-D>, otherwise you will lose the crontab file.

5. Example of use

Example 1: Execute command every 1 minute

Order:

* * * * * command

 

Example 2: Execution on the 3rd and 15th minutes of every hour

Order:

  3,15 * * * * command

 

Example 3: Execute at the 3rd and 15th minutes from 8am to 11am

Order:

  3,15 8-11 * * * command

 

Example 4: Execute every two days at the 3rd and 15th minutes from 8:00 am to 11:00 am

Order:

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

 

Example 5: Execute every Monday at the 3rd and 15th minutes from 8:00 am to 11:00 am

Order:

  3,15 8-11 * * 1 command

 

Example 6: Restart smb at 21:30 every night 

Order:

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

 

Example 7: Restart smb at 4:45 on the 1st, 10th, and 22nd of each month 

Order:

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

 

Example 8: Restart smb at 1:10 every Saturday and Sunday

Order:

  10 1 * * 6,0 /etc/init.d/smb restart

 

Example 9: Restart smb every 30 minutes between 18:00 and 23:00 every day 

Order:

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

 

Example 10: Restart smb every Saturday at 11:00 pm 

Order:

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

 

Example 11: Restart smb every hour 

Order:

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

 

Example 12: Restart smb every hour between 11pm and 7am 

Order:

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

 

Example 13: Restart smb on the 4th of every month and every Monday to Wednesday at 11:00 

Order:

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

 

Example 14: Restart smb at 4:00 on January 1st 

Order:

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

Example 15: Execute the script in the /etc/cron.hourly directory every hour

Order:

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

illustrate:

  Run-parts is the parameter. If you remove this parameter, you can write the name of a script to run instead of the directory name.

4. Precautions for use

1. Pay attention to the environment variable problem

  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 caused by not configuring environment variables in the crontab file.

  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 are 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 java or other environment variables are used for script execution, environment variables are introduced 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 the manual execution of the script is OK, but the 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

2. Pay attention to cleaning 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, the following form can be set in the crontab file to ignore 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 first, and then the standard error is redirected to the standard output. Since the standard output has been redirected to /dev/null, the standard error will also be redirected. Directed to /dev/null, so the log output problem is solved.

3. 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 in system-level task scheduling to complete (not recommended), but vice versa. No, the task scheduling operation of the root user can be set by "crontab -uroot -e", or you can directly write the scheduling task to the /etc/crontab file. It should be noted that if you want to define a task to restart the system regularly, just The task must be placed in the /etc/crontab file, even creating a scheduled system restart task under the root user is invalid.

4. Other Notes

  The newly created cron job will not be executed immediately, 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=325189572&siteId=291194637