Linux Scheduled Tasks. MD

Source: Internet
Author: User
Tags save file

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

shell=/bin/bashpath=/sbin:/bin:/usr/sbin:/usr/binmailto=roothome=/# for details see Mans 4 Crontabs  # Example of Job definition:#.----------------minute (0-59) # |  .-------------Hour (0-23) # |  |  .----------Day of Month (1-31) # |  |  |  .-------month (1-12) OR jan,feb,mar,apr ... # |  |  |  |  .----Day of Week (0-6) (sunday=0 or 7) or sun,mon,tue,wed,thu,fri,sat# |  |  |  | |# * * * * * * user-name command to be executed  

The first four rows are the environment variables that are used to configure the Crond task to run.
The first line of the shell variable specifies which shell the system will use, and this is bash,
The second line of the path variable specifies the path to the System execution command.
The third line of the mailto variable specifies that Crond's task execution information will be emailed to the root user, and if the value of the mailto variable is null, the task execution information is not sent to the user.
The four-row home variable specifies the home directory to use when executing the command or script.
The following lines describe the syntax rule definitions for crontab, which are explained in detail below.

User Task Scheduling

The user regularly performs the work, such as user data backup, timed email reminders and so on. Users can use the Crontab tool to customize their own scheduled tasks. All user-defined crontab files are saved in the/var/spool/cron directory. Its file name is the same as the user name.

User Rights file

    • /etc/cron.deny: The user listed in this file is not allowed to use the crontab command

    • /etc/cron.allow: The user listed in this file is allowed to use the crontab command

    • /var/spool/cron/: directory where all user crontab files are stored, named by user name

What the crontab file means

In the crontab file created by the user, each line represents a task, each field of each row represents a setting, its format is divided into six fields, the first five is the time setting segment, and the sixth paragraph is the command segment to execute, in the following format:

minute   hour   day   month   week   command
  • Minute: Represents minutes, which can be any integer from 0 to 59.

  • Hour: Represents the hour, which can be any integer from 0 to 23.

  • Day: Represents a date, which can be any integer from 1 to 31.

  • Month: Represents the month, which can be any integer from 1 to 12.

  • Week: Represents the day of the week, which can be any integer from 0 to 7, where 0 or 7 represents Sunday.

  • Command: The commands to execute can be either system commands or script files that you write yourself.

In each of these fields, you can also use the following special characters:

    • Asterisk (*): represents all possible values, such as the month field if it is an asterisk, the command action is executed monthly after the constraints of other fields are met.

    • Comma (,): You can specify a list range with a comma-separated value, for example, "1,2,5,7,8,9"

    • Middle Bar (-): An integer range can be represented by a middle bar between integers, such as "2-6" for "2,3,4,5,6"

    • Forward slash (/): You can specify the interval frequency of the time with a forward slash, such as "0-23/2", which is performed every two hours. A forward slash can be used with asterisks, such as */10, if used in the minute field, which means that it executes every 10 minutes.

Use of the Crontab tool using crontab format

Crontab commonly used in the following two types of formats:

crontab [-u user] [file]  
Command parameters
  • -u User: Used to set a user's crontab service, for example, "-u ixdba" means to set IXDBA user's crontab service, this parameter is usually run by the root user.

  • File:file is the name of the command file, which indicates that file is the Crontab task list and loaded into crontab. If this file is not specified on the command line, the crontab command will accept the commands typed on the standard input (keyboard) and load them into crontab.

  • -E: Edits the contents of a user's crontab file. If you do not specify a user, the crontab file for the current user is edited.

  • -L: Displays the contents of a user's crontab file, or displays the contents of the current user's crontab file if no user is specified.

  • -r: Deletes a user's crontab file from the/var/spool/cron directory and, if no user is specified, deletes the current user's crontab file by default.

  • -I: Give a confirmation prompt when deleting a user's crontab file.

Examples of Use

Every 12 hours backup/etc directory to/backups directory, save file name format "ETC-YYYY-MM-DD-HH.TAR.XZ"

# mkdir /backups# crontab -e0 */12 * * *  /usr/bin/tar -Jcf /backups/etc-`date "+\%F-\%H"`.tar.xz /etc  &>/dev/null

Weekly 2, 4, 7 backup/var/log/secure files to/logs directory, the file name format is "secure-yyyy-mm-dd.tar.gz";

# mkdir /logs# crontab -e0 0 2,4,7 * * /usr/bin/tar czf /logs/secure-`date "+\%F"`.tar.gz  &>/dev/null

Remove the line information from the current system/proc/meminfo file that starts with S or M in the/tmp/meminfo.txt file every two hours;

# crontab -e0 */2 * * *  /usr/bin/date >>/tmp/meminfo ; /usr/bin/grep ^[SM] /proc/meminfo >> /tmp/meminfo
Notes on environmental variables in use precautions

Sometimes we create a crontab, but this task cannot be executed automatically, but it is not a problem to perform this task manually, which is usually caused by not configuring environment variables in the crontab file.
When defining multiple dispatch tasks in a crontab file, one of the issues that needs special attention is the setting of environment variables, because when we perform a task manually, it is done in the current shell environment, the program can certainly find the environment variable, and the system will not load any environment variables when it automatically executes the task schedule. Therefore, you need to specify all the environment variables that are required for the task to run in the crontab file, so that the system does not have a problem when it executes the Task Scheduler.
Don't assume that Cron knows the special circumstances you need, and it doesn't really know. So you have to make sure that you provide all the necessary path and environment variables in the shelll script, except for some auto-set global variables. So note the following 3 points:

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

    • When script execution is used with Java or other environment variables, the environment variables are introduced through the source command, such as:

cat start_cbp.sh#!/bin/shsource /etc/profileexport 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, but the crontab is not executed. At this point, we must boldly suspect that environmental variables are the bane, and can try to directly introduce environmental variables in crontab to solve the problem. Such as:

0 * * * * source /etc/profile;/bin/sh /var/www/java/audit_no_count/bin/restart_audit.sh
Note Clean up the message log for system users

Each task is scheduled to execute, the system will send the task output information in the form of e-mail to the current system users, so the cumulative, log information will be very large, may affect the normal operation of the system, so it is important to redirect each task.
For example, you can set the following form in the crontab file, ignoring the 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 and then the standard error is redirected to standard output, and standard errors are redirected to/dev/null because the standard output has been redirected to/dev/null. This will solve the problem of log output.

System-level task scheduling and user-level task scheduling

System-level task scheduling is mainly to complete some maintenance operations of the system, user-level task scheduling is mainly to complete the user-defined tasks, you can put the user-level task scheduling to the system-level task scheduling to complete (not recommended), but in turn, the root user's task scheduling operation can be through the "crontab– Uroot–e "To set, you can also write the dispatch task directly to the/etc/crontab file, it should be noted that if you want to define a scheduled restart of the system task, you must put the task into the/etc/crontab file, Even the task of creating a timed restart of the system under the root user is not valid.

Other precautions
  • The newly created cron job will not execute immediately, at least 2 minutes. If you restart Cron, it will be executed immediately.

  • When the crontab suddenly fails, you can try/etc/init.d/crond restart solve the problem. Or check the log to see if a job has execution/error tail-f/var/log/cron.

  • Don't run crontab-r. It removes the user's crontab file from the crontab directory (/var/spool/cron). All crontab of the user have been deleted.

  • In Crontab, the% has a special meaning, indicating the meaning of the line break. If you want to use the words must be escaped%, such as the frequently used date ' +%y%m%d ' in the crontab is not executed, should be replaced by the date ' +%y%m%d '.

  • If it is expected that a certain time can not be executed on schedule, the next time after the boot, whether or not to the corresponding point in time to execute once, the use of anacron implementation;

Linux scheduled tasks. MD

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.