"Go" crontab command script timed to run

Source: Internet
Author: User



I. Introduction of Crond



Crond is a daemon that is used to periodically perform certain tasks or wait for certain events under Linux, similar to Scheduled tasks under Windows, when the operating system is installed, the Service tool is installed by default and the Crond process is started automatically. The Crond process periodically checks to see if there is a task to perform and automatically executes the task if there are tasks to perform.



The 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 cache data to hard disk, log cleanup, etc. In the/etc directory there is a crontab file, this is the System Task Scheduler configuration file.



The/etc/crontab file includes the following lines:


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

[[email protected] ~] #
The first four lines are used to configure the environment variables for the crond task to run, the first line of the SHELL variable specifies which shell the system uses, here is bash, the second line of the PATH variable specifies the path for the system to execute the command, and the third line of the MAILTO variable specifies The task execution information of crond will be sent to the root user via email. If the value of the MAILTO variable is empty, it means that the task execution information is not sent to the user. The HOME variable in the fourth line specifies the main used when executing the command or script. table of Contents. The meaning of the sixth to ninth lines is explained in the next section. Not much to say here.

User task scheduling: tasks that users regularly perform, such as user data backup, regular email reminders, and so on. 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

Explanation:

The users listed in this file are not allowed to use the crontab command

file:

/etc/cron.allow

Explanation:

Users listed in this file are allowed to use crontab commands

file:

/ var / spool / cron /

Explanation:

Directory where all users crontab files are stored, named after the user

 crontab file meaning:

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 sections are time setting sections and the sixth section is The command segment to be executed has the following format:

minute hour day month week command

among them:

minute: represents 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 is executed every month after the constraints of other fields are met.

Comma (,): You can specify a range of lists 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, such as "2-6" for "2,3,4,5,6"

Forward slash (/): You can use the forward slash to specify the time interval frequency, for example "0-23 / 2" means that it is executed every two hours. At the same time, forward slashes can be used with asterisks, such as * / 10. If used in the minute field, it means that it is executed every ten minutes.

 

Second, 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 see if the crontab service is set to start at startup, execute the command:

ntsysv

Join the startup automatically:

chkconfig --level 35 crond on

 

Third, the crontab command

1. Command format:

crontab [-u user] file

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

2. Command function:

With the crontab command, we can execute specified system instructions or shell script scripts at regular intervals. The unit of the time interval can be any combination of minutes, hours, days, months, weeks, and more. This command is very suitable 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, which means to use file as a crontab task list file and load 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 content of a user's crontab file. If no user is specified, it means to edit the crontab file of the current user.

-l: Display the content of the crontab file of a user. If no user is specified, the content of the crontab file of the current user 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 is deleted by default.

-i: prompt for confirmation when deleting the user's crontab file.

4. Common methods:

1). Create a new crontab file

 

Before considering submitting a crontab file to the cron process, the first thing 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 the same, then you edit the .profile file in the $ HOME directory and add a line like this:

EDITOR = vi; export EDITOR

Then save and exit. Consider creating a file named <user> cron, where <user> is the username, 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 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 tell at a glance when the system stopped working from the last displayed time. In some systems, the console is represented by tty1, and the above example can be modified accordingly according to the actual situation. In order to submit the crontab file you just created, you can use this newly created file as a parameter 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 user name (that is, 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 $ HO M E directory:

     $ crontab -l> $ HOME / mycron

    In this way, once the crontab file is accidentally deleted by mistake, you can quickly restore it 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 E D I TO R environment variable is set to vi, then you can use cr to edit the crontab file. The corresponding command is:

     $ crontab -e

You can modify the crontab file and exit like you would edit any other file with vi. If some entries are modified or new entries are added, cron will perform the necessary integrity checks when saving the file. If one of these fields has a value outside the allowed range, it will prompt you.

When 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 {} \;

Save and exit now. It is best to add a comment on each entry in the crontab file so that you can know its function, running time, and more 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 by mistake, assuming you have a backup in your $ HOOM 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 file name of your copy in the $ HOME directory.

I suggest you keep a copy of the file in your $ HOOM directory. I had a similar experience and deleted the crontab file several times by mistake (because the r key was right next to the e key). This is why some system documentation recommends not to edit the crontab file directly, but to edit a copy of the file and then resubmit the new file.

Some crontab variants are weird, so be careful when using crontab commands. If any options are missing, crontab may open an empty file or look like an empty file. Hit delete at this time to exit, do not press <Ctrl-D>, otherwise you will lose the crontab file.

6) .crontab modify the default editor

The default editor of crontab is nano. Modify the default editor of crontab to vi or other editors. Method 1: export EDITOR = "/ usr / bin / vim"; crontab -e Method 2: Execute the command: select-editor and then select the editor.
5. Use case

Example 1: execute command every 1 minute

command:

* * * * * command

Example 2: 3rd and 15th minute of every hour

command:

3,15 * * * * command

Example 3: From 8 am to 11 am 3 and 15 minutes

command:

3,15 8-11 * * * command

Example 4: 3 and 15 minutes from 8 am to 11 am every other day

command:

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

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

command:

3,15 8-11 * * 1 command

Example 6: Restart smb at 21:30 every night

command:

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

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

command:

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

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

command:

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

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

command:

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

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

command:

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

Example 11: Restart smb every hour

command:

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

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

command:

* 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

command:

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

Example 14: Restart smb at 4 o'clock on January 1st

command:

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

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

command:

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

Explanation:

run-parts parameter, if you remove this parameter, you can write the name of a script to run instead of the directory name
 

Fourth, precautions for use

Attention to environmental variables

Sometimes we create a crontab, but this task cannot be performed automatically, but it is not a problem to manually execute this task. This situation is generally caused by the environment variables not configured in the crontab file.

When defining multiple scheduled tasks in a crontab file, one issue that requires special attention is the setting of environment variables, because when we manually perform a task, it is performed in the current shell environment. Of course, the program can find the environment variables, and the system When the task scheduling is performed automatically, no environment variables are loaded. Therefore, all environment variables required for task running need to be specified in the crontab file, so that there is no problem when the system performs task scheduling.

Don't assume that cron knows the special environment it needs, it doesn't. So you need to ensure that all necessary path and environment variables are provided 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, the 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 script is executed manually, but crontab is not executed. At this time, you must boldly suspect that the environment variable is the cause of the problem, 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 up the mail logs of system users

After the execution of each task is scheduled, the system will send the task output information to the current system user in the form of email. In this way, the log information will be very large and may affect the normal operation of the system. Therefore, each task will be redirected. Processing is very important.

For example, you can set the following form 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 is also heavy. Directed to / dev / null, so the log output issue is resolved.

 

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

System-level task scheduling mainly completes some maintenance operations of the system. User-level task scheduling mainly completes some user-defined tasks. User-level task scheduling can be completed by system-level task scheduling (not recommended), but the other way around is No, the task scheduling operation of the root user can be set by "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 define a task to restart the system at regular intervals, The task must be placed in the / etc / crontab file, even if you create a task to restart the system regularly under the root user is invalid.

4. Other considerations

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 / error tail -f / var / log / cron.

Don't run crontab -r at random. It deletes the user's Crontab file from the Crontab directory (/ var / spool / cron). All crontabs that deleted this user are gone.

% Has a special meaning in crontab, meaning the meaning of a newline. If you want to use it, you must escape \%. For example, the commonly used date '+% Y% m% d' will not be executed in crontab. You should replace it with date '+ \% Y \% m \% d' .

 

Original address: http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html

[Go] crontab command Script runs at regular intervals

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.