Linux timed Execution Task crontab command usage

Source: Internet
Author: User
Tags rsyslog

The Linux system's scheduled tasks are controlled by cron (Crond), the system service. Linux systems have a lot of planned work on them, so this system service is started by default. In addition, because the user can set up scheduled tasks themselves, the Linux system also provides a command for the user to control the Scheduled tasks: crontab command

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 execution of timed tasks under Linux depends on the daemon.

The task scheduling under Linux is divided into two categories, system task scheduling and user task scheduling.
1) System task scheduling: The system periodically to perform the work, such as write cache data to the hard disk, log cleanup and so on. In the/etc directory there is a crontab file, this is the System Task Scheduler configuration file. By editing the file, we can set the scheduled execution task.

2) User Task scheduling: Users to perform regular work, such as user data backup, scheduled email reminders. Users can use the crontab command to customize their own scheduled tasks. All user-defined crontab files are stored in the/var/spool/cron directory with the same file name as the user name.

The crontab command is commonly used in Unix-and Unix-like operating systems to set instructions that are executed periodically. The command reads the instruction from the standard input device and stores it in a "crontab" file for later reading and execution. The word derives from the Greek language Chronos (Χρ?νος), which was originally meant to be time.

Typically, the crontab stored instruction is activated by the daemon, the Crond process runs in the background, and every minute checks whether a scheduled job needs to be performed. This type of work is generally called cron jobs.

Basic usage of the crontab command 1, crontab command options
Crontab-u   //Set a user's Cron service, the general root user needs this parameter when executing this command crontab-l   //list details of a user cron service Crontab-r   // Delete a user's cron service crontab-e   //Edit a user's cron service

For example, root to view your cron settings: Crontab-u root-l

Again, for example, Root wants to delete Fred's cron settings: Crontab-u fred-r

2, crontab command special symbol
"*"  represents all numbers within the range of values. This requires special attention "/"  on behalf of each meaning, such as */10, if used in the minute field, which represents every 10 minutes of execution. "-"  represents a number to a number, such as "2-6" for "2,3,4,5,6", "  specifies a list range, for example," 1,2,5,7,8,9 "
3. crontab command timed task file format

The file format of the Crontab Dispatch task is generally as follows:

1234567891011
Minute   Hour Day month    Dayofweek     command minute     hour    days     month       Day weekly       order Each field represents the following meaning: Minute the task in the first few minutes of each hour, the range is 0–59hour hours of the day to perform the task, and the scope is          0–23day the number of days of the month to           perform the task, ranging from 1–31month         the first months of the year to perform this task, ranging from 1–12 or jan,feb,mar,apr ... DayOfWeek     the day of the week to perform the task, either 0–6 or Sun,mon,tue,wed,thu,fri,satcommand       specifies the program to be executed in these fields except "Command" is a field that must be specified each time, other fields are optional

Here are some common notation.

5:30 execution of the LS command per day

1
     5 * * *     ls

1:10 execution of LS command per Saturday, Sunday

1
     1       *        *    6,0    ls

Note: 0 for Sunday, 1 for the Week 1, and so on, can also be expressed in English, Sun said Sunday, Mon said Monday and so on.

The LS command is executed every hour, it should be at 0 minutes.

1
* */1 * * *     ls

Note: */n is not supported on some Linux systems, and errors may occur.

Every day 7:50 executes all executables in the/etc/cron.daily directory as root

1
   7 * * *     root     run-parts   /etc/cron.daily

Note: The Run-parts parameter indicates that all executable files in the following directory are executed. Root indicates that the executable file under the directory is executed as root.

Add timed execution tasks

As described in the first section, there are two ways to add a dispatch task:
1) in the command line input: Crontab-e then add the corresponding task, Wq save the disk to exit. The format of the Add Task command is described in more detail in the previous section. This command edits the cron file of the corresponding user under/var/spool/cron, which belongs to the user Task Scheduler.

2) directly edit the/etc/crontab file, that is, vi/etc/crontab, add the corresponding task, belong to the system task scheduling.
Crond process every minute not only to read all the files within the/var/spool/cron, but also to read a/etc/crontab, so we configure this file can also be scheduled to perform tasks. The crontab configuration is for a user, while the edit/etc/crontab is a task for the system. The file format for this file is:

1234567891011
Shell=/bin/bashpath=/sbin:/bin:/usr/sbin:/usr/bin  //environment variable Mailto=root      //If an error occurs, or if there is data output, the data is sent to this account as an email home= ///           user Run path, here is the root directory # RUN-PARTS01 * * * *     root run-parts/etc/cron.hourly          //Hourly execution/etc/ Script within cron.hourly   4 * *   *     root run-parts/etc/cron.daily           //Daily execution/etc/ Script within cron.daily   4   *   *   0     root run-parts/etc/cron.weekly          //Weekly execution/etc/ Script within cron.weekly   4   1   *   *     root run-parts/etc/cron.monthly         //Monthly go to execute/etc/ Script within cron.monthly 0 * * * *     root/root/vncrestart_tennfy.sh          //Hourly execution Vncrestart_ tennfy.sh file

In the last act we add ourselves to the timed task, which is to execute the vncrestart_tennfy.sh file every hour, where vncrestart_tennfy.sh must be an executable file.

Precautions

There are some noteworthy areas in the use of crontab, here is a brief introduction.

1. Clean up user mail

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:

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

2. Cron Job Execution Time issue

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

Summary This article describes the common use of Linux timed tasks, including two ways: 1) system task scheduling, that is, by editing/etc/crontab to add timed tasks, 2) User task scheduling, that is, the CRONTAB-E command to add a timed task. In the writing of shell scripts, we often use the first method to add timed tasks. Crontab Scheduled tasks do not perform cause 1, script syntax error

When the crontab script is not scheduled to execute, you first need to check the script syntax for any problems.

2. Environmental variables

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. We perform tasks manually in the current shell environment, the program can find the environment variables, and the system automatically perform task scheduling, will not load any environment variables. Therefore, we need to provide all the necessary path and environment variables in the shelll script.

The main points to note are the following three:

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

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

12345
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 &

3) When the script is executed manually, but 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:

1
0 * * * *  /etc/profile;/bin/sh/var/www/java/audit_no_count/bin/restart_audit.sh
3, the system task scheduling and User task scheduling system task scheduling mainly to complete the system of some maintenance operations, user task scheduling mainly to complete the user-defined tasks, you can put the user task scheduling to the system task scheduling to complete (not recommended), but the reverse is not, The root user's Task scheduler can be set by "crontab–uroot–e", or the dispatch task can be written directly to the/etc/crontab file, it is important to note that if you want to define a task that periodically restarts the system, you must put the task into/etc/ crontab files, even the task of creating a timed restart system under the root user is not valid.!!! When the above three methods still cannot solve the environment variable problem, you can put the user task scheduling to the system task scheduling to complete the crontab scheduled task does not perform the solution 1, view crontab execution record under Ubuntu installed Crontab, The system default is not to turn on crontab logging, the way to enable the Crontab log:
Modify the Rsyslog file to delete the # before the #cron.* in the/etc/rsyslog.d/50-default.conf file;
Restart Rsyslog Services service Rsyslog restart;
Restart the Cron Services service cron Restart, as follows:
More/var/log/cron.log;
You can view the log file at run time if it appears in the log file:
The code is as follows:
No MTA installed, discarding output
Then that is, Crontab executes the script is not directly wrong information output, but will be sent in the form of mail to your mailbox, this time you need a mail server, if you do not install the mail server, it will report this error. If it is a test, you can use the following method to solve:
After each timed script, add:
The code is as follows: >/dev/null 2>&1

Linux timed Execution Task crontab command usage

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.