Home >System Tutorial >LINUX >Task scheduling under Linux is divided into two types of user crontab services

Task scheduling under Linux is divided into two types of user crontab services

WBOY
WBOYforward
2024-03-11 08:00:231284browse

First issue the command:

1. Command format:

crontab[-user]file

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

2. Command function:

Through the crontab command, we can execute specified system instructions or shellscript scripts at fixed intervals. The unit of time interval can be minutes, hours, days, months, weeks, or any combination of above. This command is especially suitable for periodic log analysis or data backup.

3. Command parameters:

-user: Used to set the crontab service of a certain user. For example, "-uixdba" means setting the crontab service of the ixdba user. This parameter is usually run by the root user.

file: file is the name of the command file, which means that file is used as the task list file of crontab and loaded into crontab. If this file is not specified on the command line, the crontab command will accept commands typed on standard input (mouse) and load them into crontab.

-e: Edit the contents of a user's crontab file. If no user is specified, it means editing the crontab file of the current user.

-l: Display the crontab file content of a certain user. If the user is not specified, it means displaying the crontab file content of the current user.

-r: Delete a user's crontab file from the /var/spool/cron directory. If no user is specified, the current user's crontab file will be deleted by default.

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

More details:

1. Introduction to crond

crond is a daemon process used under Linux to periodically perform certain tasks or wait for processing of individual incidents. It is similar to scheduled tasks under Windows. When the operating system is installed, this service tool will be installed by default, and it will Manually start the crond process. The crond process will regularly detect whether there are tasks to be executed every minute. If there are tasks to be executed, the tasks will be executed manually.

Task scheduling under Linux is divided into two categories, system task scheduling and user task scheduling.

System task scheduling: The work that the system performs periodically, such as writing cached data to the hard disk, clearing logs, etc. There is a crontab file in the /etc directory, which is the configuration file for system task scheduling.

/etc/crontab file includes the following lines:

[root@localhost~]#cat/etc/crontab

SHELL=/bin/bash

PATH=/sbin:/bin:/usr/sbin:/usr/bin

MAILTO=""HOME=/

#run-parts

51****rootrun-parts/etc/cron.hourly

247***rootrun-parts/etc/cron.daily

224**0rootrun-parts/etc/cron.weekly

4241**rootrun-parts/etc/cron.monthly

[root@localhost~]

#The first four lines are used to configure the environment variables for running the crond task. The SHELL variable in the first line specifies which shell the system will use, here is bash. The PATH variable in the second line specifies the path for the system to execute the command. The third line The MAILTO variable specifies that crond's task execution information 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 will not be sent to the user. The HOME variable in the fourth line specifies that the command or script will be executed. The home directory used. The meaning expressed by lines six to nine will be elaborated on in the next section. Not much to say here.

User task scheduling: tasks that users need to perform regularly, such as user data backup, regular email reminders, etc. 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 consistent with the user name.

User permissions file:

document:

/etc/cron.deny

illustrate:

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

document:

/etc/cron.allow

illustrate:

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

document:

/var/spool/cron/

illustrate:

The directory where all user crontab files are stored, named after the user name

The meaning of crontab file:

In the crontab file built by the user, each line represents a task, and each array in each line represents a setting. Its format is divided into six arrays. The first five segments are time setting segments. The sixth segment is the command segment to be executed, the format is as follows:

minutehourdaymonthweekcommand

in:

minute: represents the minute, which can be any integer from 0 to 59.

hour: represents the hour, which can be any integer from 0 to 23.

day: represents 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 can be a system command or a script file compiled by yourself.

In each of the above arrays, you can also use the following special characters:

Asterisk (*): represents all possible values. For example, if the month array is an asterisk, it means that the command operation will be executed every month after the obstacle conditions of other arrays are met.

Colon (,): You can use colon-separated values ​​to specify a list range, for example, "1,2,5,7,8,9"

Zhong bar (-): You can use the middle bar between integers to represent an integer rangeLinux scheduled tasks are not executed, such as "2-6" means "2,3,4,5,6 ”

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

2. crond service

Install crontab:

yuminstallcrontabs

Service operation instructions:

/sbin/servicecrondstart//Start service

/sbin/servicecrondstop//Turn off the service

/sbin/servicecrondrestart//Restart service

/sbin/servicecrondreload//Reload configuration

View crontab service status:

servicecrondstatus

linux任务计划不生效_linux任务计划执行脚本_linux 计划任务没执行

Automatically start the crontab service:

servicecrondstart

Check whether the crontab service has been set to start at boot, execute the command:

ntsysv

Add manual startup at boot:

chkconfig–level35crondon

3. Interpretation of crontab command

1. Command format:

crontab[-user]file

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

2. Command function:

Through the crontab command, we can execute specified system instructions or shellscript scripts at fixed intervals. The unit of time interval can be minutes, hours, days, months, weeks, or any combination of above. This command is especially suitable for periodic log analysis or data backup.

3. Command parameters:

-user: Used to set the crontab service of a certain user. For example, "-uixdba" means setting the crontab service of the ixdba user. This parameter is usually run by the root user.

file: file is the name of the command file, which means that file is used as the task list file of crontab and loaded into crontab. If this file is not specified on the command line, the crontab command will accept commands typed on standard input (mouse) and load them into crontab.

-e: Edit the contents of a user's crontab file. If you do not specify a user, it means editing the crontab file of the current user.

-l: Display the crontab file content of a certain user. If the user is not specified, it means displaying the crontab file content of the current user.

-r: Delete a user's crontab file from the /var/spool/cron directory. If no user is specified, the current user's crontab file will be deleted by default.

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

4. Commonly used 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 edit the .profile file in the $HOME directory linux scheduled task is not executed, and add this line:

EDITOR=vi;exportEDITOR

Save and exit after that. Might as well create a file called cron, where is the username, for example, davecron. Add the following content to this file.

#(putyourowninitialshere)echothedatetotheconsoleevery

#15minutesbetween6pmand6am

0,15,30,4518-06***/bin/echo'date'>/dev/console

Save and exit. Make sure the next 5 fields are separated by spaces.

In the previous 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 time displayed. In some systems, tty1 is used to represent the console, and the examples inside can be changed 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 of the cron command:

$crontabdavecron

Now the file has been submitted to the cron process, which 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 (ie dave).

2). List crontab files

To enumerate crontab files, you can use:

$crontab-l

0,15,30,45,18-06***/bin/echo`date`>dev/tty1

You will see content similar to the previous one. You can use these methods to make a backup of the crontab file in the $HOME directory:

$crontab-l>$HOME/mycron

In this way, once the crontab file is accidentally deleted, it can be quickly restored 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 EDITOR environment variable is set to vi, you can use vi to edit the crontab file. The corresponding command is:

$crontab-e

You can change the crontab file and exit just like using vi to edit any other file. If individual entries are changed or new entries are added, cron will perform the necessary integrity checks on the file when saving it. If a value in one of the fields exceeds the allowed range, it will prompt you.

When we edit the crontab file, we may add new entries. For example, add the following:

#DT:deletecorefiles,at3.30amon1,7,14,21,26,26daysofeachmonth

3031,7,14,21,26**/bin/find-name"core'-execrm{};

Save and exit now. It is best to add a comment to each entry in the crontab file so that you know its function, running time, and more importantly, which user's job it is.

Now let us use the crontab-l command mentioned above to list all its information:

$crontab-l

#(crondaveinstalledonTueMay413:07:431999)

#DT:echthedatetotheconsoleevery30minites

0,15,30,4518-06***/bin/echo`date`>/dev/tty1

#DT:deletecorefiles,at3.30amon1,7,14,21,26,26daysofeachmonth

3031,7,14,21,26**/bin/find-name"core'-execrm{};

4).Delete crontab file

To delete the crontab file, you can use:

$crontab-r

5).Restore lost crontab file

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

$crontab

Among them, is the file name of your copy in the $HOME directory.

I recommend that you save a copy of this file in your $HOME directory. I have had a similar experience and deleted the crontab file several times (because the r key is immediately to the left of 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 a little weird, so be careful when using the crontab command. If any options are omitted, crontab may open an empty file, or appear to be an empty file. At this time, hit the delete key to exit. Do not press it, otherwise you will lose the crontab file.

5. Usage examples

Example 1: Execute command every 1 minute

Order:

*****command

Example 2: Execution at the 3rd and 15th minutes of every hour

Order:

3,15****command

Example 3: Execute at the 3rd and 15th minutes from 8pm to 11pm

Order:

3,158-11***command

Example 4: Execute at the 3rd and 15th minutes from 8 am to 11 am every seven days

Order:

3,158-11*/2**command

Example 5: Execution at the 3rd and 15th minutes from 8:00 to 11:00 every Monday morning

Order:

3,158-11**1command

Example 6: Restart smb at 21:30 in the evening

Order:

3021***/etc/init.d/smbrestart

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

Order:

4541,10,22**/etc/init.d/smbrestart

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

Order:

101**6,0/etc/init.d/smbrestart

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

Order:

0,3018-23***/etc/init.d/smbrestart

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

Order:

023**6/etc/init.d/smbrestart

Example 11: Restart smb every hour

Order:

**/1***/etc/init.d/smbrestart

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

Order:

*23-7/1***/etc/init.d/smbrestart

Example 13: Restart smb on the 4th of every month and 11 o'clock every Monday to Friday

Order:

0114*mon-wed/etc/init.d/smbrestart

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

Order:

041jan*/etc/init.d/smbrestart

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

Order:

01****rootrun-parts/etc/cron.hourly

illustrate:

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

4. Precautions for use

1. Pay attention to environment variable issues

Sometimes we create a crontab, and this task is difficult to perform manually, but there is no problem in automatically executing this task. These situations are usually caused by environment variables not being configured in the crontab file.

When defining multiple scheduling tasks in a crontab file, one issue that requires great attention is the setting of environment variables. Because when we automatically execute a task, it is performed in the current shell environment, and the program can actually find the environment variables. , and when the system manually performs task scheduling, it will not load any environment variables. For this reason, the introduction of the Linux operating system requires that all environment variables required for task running be specified in the crontab file. In this way, when the system performs task scheduling, there will be no Problem.

Don't assume that cron knows the special circumstances required, it doesn't seem to. So you have to make sure to provide all necessary paths and environment variables in the shell script, not just some manually set global variables. So pay attention to the following 3 points:

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

2) When script execution requires java or other environment variables, introduce the environment variables through the source command, such as:

catstart_cbp.sh

#!/bin/sh

source/etc/profile

exportRUN_CONF=/home/d139/conf/platform/cbp/cbp_jboss.conf

/usr/local/jboss-4.0.5/bin/run.sh-cmev&

3) When the automatic execution of the script is OK, but the crontab is not executed. At this time, you must boldly suspect that environment variables are to blame, and you can try to directly introduce environment variables in crontab to solve the problem. like:

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

2. Pay attention to clearing the email logs of system users

After each task is scheduled to be executed, the system will send the task output information to the current system user via email. Over time, the log information will be extremely large, which may affect the normal operation of the system. Linux operation and maintenance blog, therefore , it is very important to redirect each task.

For example, you can set the following method in the crontab file to ignore the log output:

0*/3***/usr/local/apache2/apachectlrestart>/dev/null2>&1

"/dev/null2>&1" means to first redirect the standard output to /dev/null, and then redirect the standard error to the standard output, because the standard output has already been redirected to /dev/null, so the standard error is also It will be redirected to /dev/null, so the log output problem is solved.

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 in system-level task scheduling (this is not recommended), and The reverse does not work. The root user's task scheduling operation can be set through "crontab-uroot-e", or the scheduling task can be written 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 place the task in the /etc/crontab file, although creating a task to regularly restart the system under the root user is also invalid.

4.Other notes

The newly created cronjob will not be executed immediately. It will take at least 2 minutes to execute. If cron is restarted, it will be executed immediately.

When crontab suddenly fails, you can try /etc/init.d/crondrestart to solve the problem. Or check the log to see if a job is executed/report an error tail-f/var/log/cron.

Never run crontab-r randomly. It deletes the user's Crontab files from the Crontab directory (/var/spool/cron). After deleting all the crontabs of this user, they are gone.

% has a special meaning in crontab, which means line break. If you want to use it, you must use the wildcard %. For example, the commonly used date' %Y%m%d' will not be executed in crontab and should be replaced by date' %Y%m%d'.

New description: Check the log record vim-f/var/log/cron, which is the vim scheduled task log path, check whether the scheduled task is enabled servicecrondstatus

The above is the detailed content of Task scheduling under Linux is divided into two types of user crontab services. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:itcool.net. If there is any infringement, please contact admin@php.cn delete