Linux Command Learning Note: crontab command

Source: Internet
Author: User
Tags delete key

The previous day learned that the at command is for routine scheduled tasks that run only once, and that the Linux system is controlled by the cron (Crond) 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 scheduled tasks: the crontab command. I. Crond profile 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 has a crontab file, this is the System Task Scheduler configuration file. /etc/The crontab file includes the following lines: [[email protected]~]#Cat/etc/crontab SHELL=/bin/Bashpath=/sbin:/bin:/usr/sbin:/usr/Binmailto=""home=/# Run-PartsWuyi* * * * Root run-parts/etc/cron.hourly - 7* * * Root run-parts/etc/cron.daily A 4* *0Root run-parts/etc/cron.weekly the 4 1* * Root run-parts/etc/Cron.monthly[[email protected]~] #前四行是用来配置crond任务运行的环境变量, the first line of the shell variable specifies which shell the system will use, this is bash, and the second row 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, and the home variable in line fourth specifies the home directory to use when executing the command or script. The meaning of line sixth to Nineth is described in detail in the next section. There's not much to say here. User Task scheduling: Users to perform regular work, such as user data backup, scheduled 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/the cron directory. Its file name is the same as the user name. User permissions file: File:/etc/Cron.deny Description: The user listed in this file is not allowed to use the crontab command file:/etc/Cron.allow Description: The user listed in this file is allowed to use the crontab command file:/var/spool/cron/Description: All users crontab file directory, named after the user name crontab file meaning: In the user's crontab file, each line represents a task, each field of each row represents a setting, its format is divided into six fields, the first five paragraphs is the time setting segment, The sixth paragraph is the command segment to execute, in the following format: Minute hour day Month Week command where: minute: Represents minutes, 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, indicates that the command action is executed monthly after the constraints of the other fields are met. Comma (,): You can specify a list range with a comma-separated value, for example, "1,2,5,7,8,9the Middle bar (-): You can use the middle bar between integers to represent an integer range, such as "2-6Said2,3,4,5,6"forward slash (/): You can specify the interval frequency of the time with a forward slash, for example "0- at/2"indicates that it executes every two hours. The forward slash can be used with asterisks, for example*/Ten, if used in the minute field, indicates that it is executed every 10 minutes. Second, Crond service installation crontab:Yum InstallCrontabs Service operating instructions:/sbin/service Crond Start//Start the service/sbin/service Crond Stop//Close Service/sbin/service Crond Restart//Restart Service/sbin/service Crond Reload//Reload ConfigurationView crontab Service status: Crond status Manually start the Crontab service: Services Crond start to see if the Crontab service is set to boot, Execute command: NTSYSV join start-up automatically: Chkconfig–level *Crond on third, crontab command detailed1. Command format: crontab [-U user]filecrontab [-u user] [-e |-L |-R]2. Command function: With the crontab command, we can execute specified system instructions or shell script scripts at a fixed interval of time. The units of the time interval can be any combination of minutes, hours, days, months, weeks, and more. This command is very useful for periodic log analysis or data backup. 3. 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 usually has root user to run. file: File is the name of the command file, which represents the task list file as crontab 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: Edit 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: From/var/spool/The cron directory deletes a user's crontab file, and if you do not specify a user, the crontab file for the current user is deleted by default. -I: Give the confirmation prompt 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 depends on it to determine which editor to use to edit the crontab file. 9 9%UNIX and Linux users use VI, and if you do, you edit the. profile file in the home directory, adding a line like this: editor=VI; export editor and then save and exit. You might want to create a name<user> cron files, where <user>is the user name, for example, Davecron.         Add the following to the file. # (Put your own initials here)EchoTheDateTo the console every # 15minutes between 6pm and 6am0, the, -, $  -- .* * * */bin/Echo 'Date'>/dev/Console to save and exit. Make sure that the previous 5 fields are separated by spaces. In the example above, the system will output the current time to the console every 1 to 5 minutes. If the system crashes or hangs, you can see at what time the system stopped working at the last displayed time. In some systems, the use of tty1 to represent the console, according to the actual situation of the above example can be modified accordingly. In order to submit the crontab file you just created, you can take this newly created file as a parameter to the cron command: $ crontab Davecron Now the file has been submitted to the cron process and it will run every 1 5 minutes. At the same time, a copy of the newly created file has been placed in/var/spool/in the cron directory, the file name is the user name (that is, Dave). 2). Lists crontab files in order to list crontab files, you can use: $ crontab-L0, the, -, $, -- .* * * */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 This way, once you accidentally delete the crontab file, you can quickly recover 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 V I, then you can use VI to edit the crontab file, the corresponding command is: $ crontab-e can modify the crontab file and exit as if you were editing any other file using V I. If some entries are modified or a new entry is added, C R o N will perform the necessary integrity checks on the file when it is saved. If one of the fields has a value that exceeds the allowable range, it will prompt you. When we edit the crontab file, we may not be adding a new entry. For example, add the following article: # Dt:delete core Files,at3.30am on1,7, -, +, -, -Days of each month - 3 1,7, -, +, -* */bin/Find-name"Core '-exec rm {} \;Save and exit now. It is best to add a comment above each entry in the crontab file, so that you can know its function, run time, and, more importantly, what user's job it is. Now let's use the crontab we talked about earlier.-The L command lists all of its information: $ crontab-L # (Crondave installed on Tue4  -: -: + 1999) # Dt:ech theDateTo the console every -minites0, the, -, $  -- .* * * */bin/Echo`Date' >/dev/tty1 # dt:delete Core Files,at3.30am on1,7, -, +, -, -Days of each month - 3 1,7, -, +, -* */bin/Find-name"Core '-exec rm {} \;4). Delete crontab file to delete the crontab file, you can use: $ crontab-R5). Recover lost crontab files if you accidentally delete the crontab file, assuming you have a backup in your own $ H O-e directory, you can copy it to/var/spool/cron/<username>, where <username>is the user name. If the copy cannot be completed due to a permissions issue, you can use: $ crontab<filename>among them,<filename>is the file name of the copy you have in the $ H O M e directory. I recommend that you save a copy of the file in your own $ H O M directory. I have had a similar experience, several times accidentally deleted the crontab file (because the R key is close to the E key to the right). This is why some system documentation does not recommend editing the crontab file directly, but instead edits a copy of the file and then resubmit the new file. Some variants of crontab are somewhat bizarre, 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. Click the Delete key to exit and do not press<Ctrl-D>, or you will lose the crontab file. 5. Use instance Instance 1: Executes command commands every 1 minutes:* * * * *Command Instance 2: the 3rd and 15 minutes of the hour are executed:3, the* * * *Command Instance 3: Execute commands at 3rd and 15 minutes from 8 o'clock in the morning to 11:3, the 8- One* * *Command Example 4: Every two days from 8 o'clock in the morning to 11 points in the 3rd and 15 minutes of the execution of the commands:3, the 8- One*/2* *Command Instance 5: Every Monday from 8 o'clock in the morning to 11 in the 3rd and 15 minutes execution of commands:3, the 8- One* *1Command instance 6:21:30 restart SMB command per night: -  +* * * */etc/init.d/SMB Restart Instance 7:1 per month,Ten, the 4:45 restart SMB command on 22nd: $ 4 1,Ten, A* */etc/init.d/SMB Restart Instance 8:1:10 restart SMB command per Saturday, Sunday:Ten 1* *6,0/etc/init.d/SMB Restart Instance 9: The SMB command restarts every 30 minutes from 18:00 to 23:00 every day:0, -  -- at* * * */etc/init.d/SMB Restart Instance 10: Every Saturday night:xxpm Restart SMB command:0  at* *6/etc/init.d/SMB Restart Instance 11: Restart SMB command every hour:* */1* * * */etc/init.d/SMB Restart Instance 12: From 11 o'clock to 7 in the morning, restart the SMB command every hour:* at-7/1* * * */etc/init.d/SMB Restart Instance 13:4th per month with 11-point restart SMB command from Monday to Wednesday:0  One 4* mon-wed/etc/init.d/SMB Restart Instance 14: January 1 4-point restart SMB command:0 4 1Jan */etc/init.d/SMB Restart Instance 15: Hourly Execution/etc/script commands in the Cron.hourly directory: on* * * * Root run-parts/etc/cron.hourly Description: Run-parts This parameter, if you remove this parameter, then you can write to run a script name, instead of the directory name of four, the use of considerations1Note Environment Variables Sometimes we create a crontab, but this task does not execute automatically, but it is not a problem to perform this task manually, which is usually caused by the absence of a configuration environment variable 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:1write the global path when the file path is involved in the script;2when script execution is used with Java or other environment variables, the environment variables are introduced through the source command, such as:CatSTART_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 &3When you manually execute the script 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* * * * . /etc/profile;/bin/SH/var/www/java/audit_no_count/bin/restart_audit.SH2Note that cleaning up the system user's mail logs each task is scheduled to execute, the system will send the task output information through e-mail to the current system users, so that 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"indicates that standard output is first redirected to/dev/NULL, and then redirect the standard error to standard output, since standard output has been redirected to the/dev/NULL, so standard errors are redirected to/dev/NULL, so the log output problem is resolved. 3System-level task scheduling and user-level task scheduling system-level task scheduling mainly to complete some of the system's maintenance operations, user-level task scheduling mainly complete 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's Task scheduler can be set by "crontab–uroot–e", or the dispatch task can be written directly/etc/crontab file, it is important to note that if you want to define a task that periodically restarts the system, you must place the task/etc/crontab files, even the task of creating a timed restart system under the root user is not valid. 4Other considerations 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 is executed/Error Tail-f/var/log/Cron. Don't run crontab .-R. It is from the crontab directory (/var/spool/cron) To delete the user's crontab file. All crontab of the user have been deleted. In the crontab% is a special meaning, meaning that the line is wrapped. If it is to be used, it must be escaped \%, such as the frequently used date ' +%y%m%d ' is not executed in crontab, it should be replaced by date '+\%y\%m\%d '. Crontab multiple commands can be placed on a single line, and their execution depends on the delimiter used between the commands. If each command is separated by a semicolon (;) is separated, then the command executes continuously if each command is&&, then these commands will be executed all the time, and if there is a wrong command in the middle, then the subsequent command is no longer executed, if each command is double vertical (||) separators, if the command encounters a command that can be executed successfully, then the command stops executing, and all subsequent commands will not be executed, even after the correct command is followed. If the command fails at the beginning, it executes | | After the next command, until it encounters a command that can be executed successfully, and if all fails, all of these failed commands will be tried once

Linux Command Learning Note: crontab command

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.