Linux timed tasks do not run automatically __linux

Source: Internet
Author: User
Tags delete key

Requirements Background: Set up a Hadoop virtual machine distributed cluster environment, the need for regular clock synchronization to ensure that the machine time in the cluster is synchronized.

Design: Use Linux timing Task Crontab command, constantly timed from clock server synchronization time

Implementation : Under Root, execute command:crontab-e, that is, enter the set editing interface of the scheduled task.

Edit Input:

* * * * * * * ntpdate pool.ntp.org//Timing SET command parameters to be executed periodically

That is, the NTP synchronization time per minute,

question: But no matter how it is executed.

Resolution: Finally, the following information is referenced (see chapters I and IV), after the path of the NTP command is fully completed, the task is automatically executed, as follows: * * * * * * * /usr/sbin/ntpdate pool.ntp.org


The following information is transferred from: http://www.cnblogs.com/intval/p/5763929.html

Linux timed Task crontab command detailed

The Linux system is controlled by a cron (Crond) system service. The Linux system already has a lot of planned work on it, so this system service is started by default. In addition, because the user can set the scheduled task themselves, the Linux system also provides the user Control Scheduling task command: crontab command.

Introduction of Crond

Crond is a daemon that is used by Linux to periodically perform certain tasks or wait to handle certain events, similar to the 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 are any tasks to perform, and if there are tasks to perform, the task is automatically performed.

The task scheduling under Linux is divided into two types: System task scheduling and user task scheduling.

System task scheduling: The work to be performed periodically by the system, such as writing cache data to hard disk, log cleaning and so on. There is a crontab file in the/etc directory, which is the configuration file for system task scheduling.

The/etc/crontab file includes the following lines:

Cat/etc/crontab

Shell=/bin/bash

Path=/sbin:/bin:/usr/sbin:/usr/bin

mailto=home=/

# Run-parts

* * * Root run-parts/etc/cron.hourly

7 * * * Root run-parts/etc/cron.daily

4 * * 0 root run-parts/etc/cron.weekly

4 1 * * Root run-parts/etc/cron.monthly


The first four lines are the environment variables that are used to configure the Crond task to run, and a shell variable that specifies which shell the system will use, this is bash, and the second line path variable specifies the path to the System execution command. The third row 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, and the home variable on line fourth specifies the master directory to use when executing the command or script. The meaning of line sixth to Nineth will be described in detail in the next section. It's not much to say here.

User Task scheduling: Tasks that users perform on a regular basis, such as user data backup, timed email reminders, and more. Users can use the Crontab tool to customize their scheduled tasks. All user-defined crontab files are saved in the/var/spool/cron directory. The file name is the same as the user name.

User Rights file:

File:

/etc/cron.deny

Description

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

File:

/etc/cron.allow

Description

Users listed in this file are allowed to use the crontab command

File:

/var/spool/cron/

Description

Directory of all user crontab files, named after user name

The meaning of the crontab file:

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

Minute hour day Month Week command

which

Minute: Represents a minute, which can be any integer from 0 to 59.

Hour: Represents an 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: Indicates the day of the week, can be any integer from 0 to 7, where 0 or 7 represent Sunday.

Command: The commands you want to execute, 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, indicates that the command operation is performed every month 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"

Medium Bar (-): You can use the middle bar between integers to represent an integer range, for example, "2-6" means "2,3,4,5,6"

Forward slash (/): You can use a forward slash to specify the interval frequency of the time, for example, "0-23/2" means to perform every two hours. The forward slash can also be used with the asterisk, such as */10, which, if used in the minute field, means that it is executed every 10 minutes.

Second, Crond service

Install Crontab:

Yum Install Crontabs

Service Operation Description:

/sbin/service crond Start//boot service

/sbin/service Crond Stop//Off service

/sbin/service crond Restart//Restart service

/sbin/service Crond Reload//Reload Configuration

/sbin/service crond Status/Start service


To see if the Crontab service is set to boot, execute the command:

Ntsysv

Join the boot auto start:

Chkconfig–level Crond on

Three, crontab order detailed

1. Command format:

crontab [-u user] File

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

2. Command function:

With the crontab command, we can execute the specified system instructions or shell script scripts at a fixed interval of time. The unit of time interval can be any combination of minutes, hours, days, months, weeks, and more. This command is designed to work with periodic log analysis or data backup.

3. Command parameters:

-u User: Used to set a user's crontab service, for example, "-u ixdba" means setting the IXDBA user's crontab service, which is typically run by the root user.

File:file is the name of the command file, which means that file will be crontab as a task list and loaded into crontab. If this file is not specified on the command line, the crontab command accepts the commands typed on the standard input (keyboard) and loads them into crontab.

-E: Edit the contents of a user's crontab file. If you do not specify a user, edit the current user's crontab file.

-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 deletes the current user's crontab file by default if no user is specified.

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

4. Common methods:

1). Create a new crontab file

One of the first things to do before considering submitting a crontab file to a cron process is to set up the environment variable editor. The cron process depends on it to determine which editor to use to edit the crontab file. 9 9 of UNIX and Linux users use VI, if you do the same, then you edit the $ home directory. Profile file in which to add one line:

Editor=vi; Export EDITOR

Then save and exit. You may wish to create a file named <user> Cron, where <user> is the user name, for example, Davecron. Add the following content to the file.

# (Put your own initials) 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 that the first 5 fields are separated by spaces.

In the example above, the system will output the current time to the console every 1 5 minutes. If the system crashes or hangs, you can see at what time the system stopped working from the last time it was displayed. In some systems, using tty1 to represent the console, the above example can be modified according to the actual situation. To submit the crontab file you just created, you can use this newly created file as a parameter to the cron command:

$ crontab Davecron

The file is now submitted to the Cron process, which will run every 1 to 5 minutes.

Also, a copy of the newly created file has been placed in the/var/spool/cron directory, and the filename is the username (that is, Dave).

2). List crontab Files

To list crontab files, you can 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 $ H O M e directory:

$ crontab-l > $HOME/mycron

In this way, once you accidentally delete the crontab file, you can use the method described in the previous section to recover quickly.

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 V I, you can edit the crontab file with V I, and the corresponding command is:

$ crontab-e

You can modify the crontab file as you would edit any other file using V I and exit. If you modify some entries or add new entries, the C R o N will perform the necessary integrity checks on the file when you save it. If one of the fields has a value that is outside the allowable range, it prompts you.

When we edit the crontab file, we may add a new entry. For example, add the following article:

# Dt:delete Core Files,at 3.30am on 1,7,14,21,26,26 days of each month

3 1,7,14,21,26 * */bin/find-name "core"-exec rm {} \;

Now save and exit. It's a good idea to add a comment above each entry in the crontab file so that you know its function, uptime, and more importantly, who knows which user's job.

Now let's list all of its information using the CRONTAB-L command we talked about earlier:

$ crontab-l

# (Crondave installed on Tue 4 13:07:43 1999)

# Dt:ech The date to the console every 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

3 1,7,14,21,26 * */bin/find-name "core"-exec rm {} \;

4). Delete crontab file

To delete a crontab file, you can use:

$ crontab-r

5. Recovery of Lost crontab files

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

$ crontab <filename>

Where,<filename> is the file name of your replica in the $ H O M e directory.

I suggest that you save a copy of the file in your own $ H O M e directory. I have had a similar experience, several times mistakenly deleted the crontab file (because the R key is close to the right of the E key). This is why some system documents do not recommend editing the crontab file directly, but instead edit a copy of the file, and then resubmit the new file.

Some crontab variants are a bit weird, so be careful when using the crontab command. If you omit any of the options, crontab may open an empty file, or it might look like an empty file. Then click the Delete key to exit, do not press <CTRL-D>, or you will lose crontab file.

5. Working with instances

Example 1: Execute command every 1 minutes
Command:
* * * * command

Example 2:3rd and 15 minutes per hour execution
Command:
3,15 * * * command

Example 3:3rd and 15 minutes from 8 o'clock in the morning to 11.
Command:
3,15 8-11 * * * command

Instance 4:3rd and 15 minutes from 8 o'clock in the morning to 11 points every two days
Command:
3,15 8-11 */2 * command

Instance 5:3rd and 15 minutes per Monday from 8 o'clock in the morning to 11.
Command:
3,15 8-11 * * 1 command

Example 6:21:30 restart SMB per night
Command:
* * * */ETC/INIT.D/SMB restart


Instance 7:4:45 Restart SMB for 1, 10, 22nd per month
Command:
4 1,10,22 * */ETC/INIT.D/SMB restart


Example 8:1:10 restart SMB per Saturday and Sunday
Command:
1 * * 6,0/ETC/INIT.D/SMB restart


Example 9: Restart SMB every 30 minutes from 18:00 to 23:00 every day
Command:
0,30 18-23 * * * */ETC/INIT.D/SMB restart


Example 10: Every Saturday night 11:00 pm reboot SMB
Command:
0 * * 6/ETC/INIT.D/SMB restart


Example 11: Restart SMB per hour
Command:
* */1 * * * */ETC/INIT.D/SMB restart


Example 12: Restart SMB every hour between 11 o'clock and 7 in the morning.
Command:
* 23-7/1 * * * */ETC/INIT.D/SMB restart

Example 13:4th for each month and restart SMB for 11 points every Monday to Wednesday
Command:
0 4 * MON-WED/ETC/INIT.D/SMB restart

Example 14: Restart SMB at 4 point January 1
Command:
0 4 1/ETC/INIT.D/SMB * Restart


Example 15: Executing scripts within the/etc/cron.hourly directory every Hour
Command:
* * * * Root run-parts/etc/cron.hourly
Description
Run-parts This parameter, if you remove this parameter, then you can write a script name to run, not a directory name


Iv. Precautions for use

Attention to environment variable problem
Sometimes we create a crontab, but this task is not automated, but it is not a problem to perform this task manually, which is typically caused by not configuring the environment variable in the crontab file.

When you define multiple scheduling tasks in the crontab file, one problem that needs special attention is the setting of environment variables, because when we perform a task manually, it is in the current shell environment, and the program can certainly find the environment variable, and the system does not load any environment variables when it performs task scheduling automatically. As a result, you need to specify all the environment variables required for the task to run in the crontab file, so that there is no problem when the system performs task scheduling.

Do not assume that Cron knows the special circumstances that are required, it does not actually know. So you have to make sure that you provide all the necessary path and environment variables in the Shelll script, in addition to some of the global variables that are automatically set. So notice the following 3 points:

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

2 when the script executes to use Java or other environment variables, the source command is used 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 &

3 When the script is executed manually OK, but crontab is not executed. At this time must be bold suspicion of environmental variables, and can try to directly introduce environmental variables in the crontab to solve the problem. Such as:

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

Note cleaning the system user's mail log
Each task scheduled execution completed, the system will send the task output information through e-mail to the current system users, so that the accumulation of 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 to ignore the log output:

0 */3 * * */usr/local/apache2/apachectl restart >/dev/null 2>&1

The "/dev/null 2>&1" means that the standard output is redirected to the/dev/null first, then the standard error is redirected to the standard output, and the standard error is redirected to the/dev/null because the standard output has been redirected to the/dev/null. This will solve the problem of log output.

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 a number of user-defined tasks, you can put user-level task scheduling to the system-level task scheduling to complete (not recommended), but the reverse is not, the root user task scheduling operations can be through the "crontab– Uroot–e "To set up, or you can write the dispatch task 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 in the/etc/crontab file, even if you create a The task of periodically restarting the system is also invalid.

Other considerations
The newly created Cron job will not be executed immediately and will take at least 2 minutes to execute. If you restart Cron, it executes immediately.

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

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

In Crontab, the% is of special meaning, indicating the meaning of line wrapping. If you want to use it must be escaped \%, such as the frequent use of the date ' +%y%m%d ' in the crontab will not be executed, should be replaced by the date ' +\%y\%m\%d '.

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.