crontab: The daemons for timed tasks , Accurate to minute , We usually write scripts when we design seconds   --> It's like an alarm clock
        Log files :  ll /var/log/cron*
        Edit the file : vim /etc/crontab       
        process :ps -ef | grep crond  ==> /etc/init.d/crond restart
        effect : Scheduled backup , Real time backup

Common command parameters

1

2

3

4

5

6

7

8

usage:  crontab [-u user] file

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

                (default operation is replace, per 1003.2)

        -e      (edit user's crontab)

        -l      (list user's crontab)

        -r      (delete user's crontab)

        -i      (prompt before deleting user's crontab)

        -s      (selinux context)

 

Classification of scheduled tasks


Linux There are two types of task scheduling , System task scheduling and user task scheduling .
    System task scheduling : What the system does periodically , For example, write cache data to hard disk 、 Log cleaning, etc .
        stay /etc/crontab file , This is the configuration file of system task scheduling .
    User task scheduling : What users do on a regular basis , For example, user data backup 、 Regular email reminders, etc .
        Users can use crontab Tools to customize your planned tasks .
        stay crontab The files are kept in /var/spool/cron Directory . The file name is the same as the user name

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

1. System timing task : For example, clean up the system log , Clean up the system cache    --> But more attention

     Query the path of the system's regular processing task :

         route 1:

            cd /etc/logrotate.d/        --> You can write timed tasks

            less syslog

         route 2:

            cat /etc/crontab   --> It is not recommended to use , But look at the format

         route 3:

             ls /etc/ | grep cron*

                 anacrontab

                 cron.d                 --> The same path 2 , You can write timed tasks  

                 cron.daily

                 cron.deny              --> Control ordinary users to use timing tasks crontab

                 cron.hourly

                 cron.monthly

                 crontab

                 cron.weekly

2. User's scheduled tasks       --> Focus

crontab File content analysis

cat /etc/crontab

image

The first four lines are used to configure crond Environment variables for task running

first line SHELL Variable specifies which system to use shell, Here is bash

The second line PATH Variable specifies the path of the system to execute the command

The third line MAILTO The variable specifies crond The task execution information of will be sent to root user

If MAILTO The value of the variable is null , The task execution information is not sent to the user

On the fourth line HOME Variable specifies the home directory to use when executing commands or scripts .

asterisk (*): Represents all possible values , Such as month Field is asterisk , It means that the command is 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 the middle bar between integers to represent an integer range , for example “2-6” Express “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 every two hours .

Small junction :
    The best way to express numbers is to use 2 Show... For Arabic numerals
    It's better not to use both weekdays and Sundays at the same time
    Timing tasks need to be annotated
    It can be directed to a log file or an empty file
    Timed tasks must be absolute paths , And the directory must exist to produce results
    crontab The service must be turned on and running

crontab Log path

1

2

3

# 【 The logs are arranged by day 】

ll /var/log/cron*

    /var/log/cron Only scripts that record whether certain plans have been executed , But whether the specific execution is correct and some information in the process of script execution is not clear linux Will send email to the user every time .

 

1

less /var/spool/mail/root

 

Common command display

install crontab:

1

yum install crontabs

crontab Service operation instructions :

1

2

3

4

5

6

7

/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 // service crond reload

see crontab Service status :

1

service crond status

Manual start crontab service :

1

service crond status

see crontab Whether the service is set to startup , Carry out orders :

1

2

Method 1 : Interface to start       ntsysv

Method 2 : Add auto start :   chkconfig –level 35 crond on

crontab -l Check the scheduled tasks list

Edit scheduled tasks

1

crontab –e

1

==》vim /var/spool/cron/root

every other 2 Minutes output time to file

1

*/2 * * * * echo `date` >> $HOME>test.txt

crontab -r Delete scheduled tasks

1

2

3

==> from /var/spool/cron Delete the user's crontab file

==> If no user is specified , Delete the current user's crontab file

 crontab –i  Deleting user's crontab Prompt for confirmation when filing

Backup crontab file

1

crontab -l > $HOME/mycron


Recover the lost crontab file

1

2

3

If you accidentally delete crontab file , Suppose you are in your own $ H O M E There is also a backup in the directory , Then you can copy it to /var/spool/cron/<username>, among <username> Is the user name . If the copy cannot be completed due to permission issues , It can be used :

crontab <filename> among ,<filename> It's you $ H O M E The file name of the copy in the directory .

There are some crontab Some of the variants of , So it's using crontab Take extra care when ordering . If any options are missing ,crontab An empty file may be opened , Or it looks like an empty file . Now knock delete Key to exit , Don't press <Ctrl-D>, Otherwise you will lose crontab file .

Hourly execution /etc/cron.hourly Scripts in the directory

1

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

every other 2 The Internet time is synchronized once a minute

1

echo "*/2 * * * * /usr/bin/ntpstat time.windows.com >/dev/null 2>&1" >> /var/spool/cron/root


Every day 3-5,17-20 every other 30 Minutes to execute the script

1

echo "*/30 [3-5],[17-20] * * * /bin/sh /home/omc/h.sh >/dev/null 2>&1" >> /var/spool/cron/root


same day 23 spot , the second day 0 Till dawn 7 spot every other 1 Minutes to execute the script

1

* 23,00-07/1 * * * /bin/sh /home/omc.h.sh


From year to year 4 From Monday to Wednesday of every week 11 Click execute script    

1

00 11 *  4 1-3 /bin/sh /home/omc/h.sh

crontab Precautions for

1. Pay attention to the environmental variables

stay crontab When multiple scheduling tasks are defined in the file , One problem that needs special attention is the setting of environment variables

1

2

3

4

5

6

7

8

9

10

# Write the global path when the file path is involved in the script ;

# Script execution uses java Or other environment variables , adopt 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.sh -c mev &

 

# When the script is executed manually OK, however crontab When life and death are not carried out . You can try in crontab Environment variables are directly introduced to solve the problem .

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

2. System level task scheduling and user level task scheduling

1

root The user's task scheduling operation can be performed through “crontab –uroot –e” To set up , You can also write scheduling tasks directly to /etc/crontab file , It should be noted that , If you want to define a task to restart the system regularly , You have to put the task on /etc/crontab file , Even in root The user's task of creating a scheduled system restart is also invalid .

3. Other matters needing attention

1

2

3

When crontab In case of sudden failure , You can try /etc/init.d/crond restart solve the problem . Or check the log to see a job Is there any implementation / Report errors tail -f /var/log/cron.

Don't run around crontab -r. It is from Crontab Catalog (/var/spool/cron) Delete the user's Crontab file . All of the user's crontab It's gone .

stay crontab in % It has a special meaning , The meaning of a new line . If you want to use it, you have to escape \%, As often used date ‘+%Y%m%d’ stay crontab It's not going to work , Should be replaced with date ‘+\%Y\%m\%d’

4. Production debugging timing task

1

2

3

4

1. Increase the frequency of executing tasks

2. Adjust system time, debug task , advance 5 minute    --> Not used in production environment

3. Output debug timing through script log Mission

4. Pay attention to the problems caused by some task commands         --> Make sure the command is correct

5.crontab Motto

1

2

3

4

5

6

7

8

9

10

11

1. Environmental variables , for example crontab Can't identify Java Environment variables of

    crontab perform shell when , Only a few environment variables can be identified , Ordinary environment variables are not recognizable , So I'm writing shell when , Best use export Redeclare variables , Make sure the script executes .

2. The best way to execute a command is to use a script

3. Script permissions plus /bin/sh, Canonical path /server/scripts

4. The time variable is escaped with a backslash , It's better to use scripts

5. Add comments to timed tasks

6.>/dev/null 2>&1   ==>&>/dev/null, Don't print the log file

7. Try to use the full path for the program script in the timing task

8. Avoid unnecessary programs and command output

9. Add comments before scheduled tasks

10. Package one level up the file directory