[Linux] crontab scheduled tasks

Crontab (cron table) is a very useful tool when you need to perform certain tasks regularly in Linux systems. It allows you to create and manage scheduled tasks based on a predetermined schedule.

1. From daemon process to crond process

1.1 Linux daemon process

According to the function of the process and the classification of running programs, processes can be divided into two major categories.

  • System process : It can perform management work such as memory resource allocation and process switching ; moreover, the operation of this process is not subject to user intervention, and even the root user cannot interfere with the operation of the system process.
  • User process : A process that is spawned by executing a user program, application program, or system program outside the kernel. Such a process can run or be shut down under the user's control.

For user processes , they can be divided into three categories: interactive processes, batch processes and daemon processes.

  • Interactive process: A process started by a shell terminal. During execution, it needs to interact with the user. It can run in the foreground or in the background.
  • Batch process: This process is a collection of processes that are responsible for starting other processes in sequence.
  • Daemon process : A daemon process is a process that runs all the time . It is often started when the Linux system starts and terminates when the system is shut down . They are independent of the control terminal and periodically perform some task or wait for some event to occur. For example, the httpd process is always running, waiting for user access. There are also commonly used crondprocesses, which are similar to Windows scheduled tasks and can periodically execute certain tasks set by the user.

1.2 Task scheduling process crond

crondIt is a daemon process used under Linux to periodically perform certain tasks or wait for processing certain events , similar to scheduled tasks under Windows. After the operating system is installed, this service tool will be installed by default, and the crond process will be automatically started. The crond process will regularly check whether there are tasks to be executed every minute . If there are tasks to be executed, the task will be automatically executed.

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

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

Open the file and you can see these contents:nvim /etc/crontab
Insert image description here

In the picture above:

  1. Line 7: Specify the shell program used by the system;
  2. Line 8: The search path of the command. (The first two lines are to set environment variables)
  3. Lines 18~21: scheduled tasks

(2) User task scheduling: tasks that users need to perform regularly, such as user data backup, regular email reminders, etc. Users can use crontabtools to customize their own scheduled tasks. All user-defined crontab files are saved in /var/spool/cronthe directory. Its file name is consistent with the user name.

2. Detailed introduction of crontab

Crontab file: Each user has an independent crontab file for storing their scheduled tasks. These files are usually located /var/spool/cron/in a directory, or there may be a first-level directory, named after the user name.

2.1 crontab command format

There are two commonly used formats for crontab:

crontab  [-u  user]  [file]         # 用于安装(载入)任务
crontab  [-u  user]  [-e|-l|-r |-i] # 用于编辑、查看、删除

The options have the following meanings:

  • -u user: Used to set the crontab service of a certain user. For example, "-u ixdba" means setting the crontab service of the ixdba user. This parameter is generally run by the root user.
  • file: file is the name of the command file, which means to use file as the task list file of crontab and load it into crontab . If this file is not specified on the command line, the crontab command will accept commands typed on the standard input (keyboard) 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 contents of a user's crontab file. If no user is specified, it means to display the contents of the crontab file of the current user.
  • -r: Delete a user's crontab file from the /var/spool/cron directory. If no user is specified, the crontab file of the current user will be deleted by default.
  • -i: Give a confirmation prompt when deleting the user's crontab file.

2.2 The meaning of crontab file

In the crontab file created by the user, each line represents a task , and each field in each line represents a setting .

Its format is divided into 7 fields. The first 5 fields are the time setting section, the 6th field is the executing user, and the 7th field is the command section to be executed. The format is as follows.

minute    hour    day    month    week   user  command

Insert image description here

in.

minute: Indicates the minute, which can be any integer from 0 to 59.
hour: Indicates the hour, which can be any integer from 0 to 23.
day: Indicates 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.
user: User name, the user who performs this task. This field can also be omitted , and tasks defined in the file will be performed by the owner of the file.
command: Indicates the command to be executed, which can be a system command or a script file written by yourself.

In each of the above fields, the following special characters can also be used.

Asterisk (*) : represents all possible values. For example, if the month field is an asterisk, it means that the command operation will be executed every month after the constraints of other fields are met.
Comma (,) : You can specify a list range with comma-separated values. For example, "1,2,5,7,8,9".
Center bar (-) : You can use a center bar between integers to represent an integer range. For example, "2-6" means "2,3,4,5,6".
Forward slash (/) : You can use forward slash to specify the time interval frequency . For example, "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 field, it means that it will be executed every 10 minutes.

2.3 Practical operation: writing crontab file

In my system, the location of the crontab file is:/var/spool/cron/crontabs/root

Open it, prepare to write a new task, and find:
Insert image description here

Prompt not to edit this file directly, but to edit another temporary file.

Editing, it must be possible to edit, as long as I have permission. But the above method may be safer, prevent errors, and increase maintainability. Then follow the recommendations.

Use the editing command: crontab -e, you will be asked to choose an editor first, and I use vim to edit.

I found that this temporary file is opened by default :
Insert image description here

Then edit it:
Insert image description here
I wrote a scheduled task for testing. Every one minute, append a line to the end of the /root/crontest.txt file. The content is the current time of the system (the date command and output redirection are used here) .

Note: I added the first two lines here to configure environment variables to prevent the command from being found when executing the task.

After editing is completed, save it and exit nvim. Then check the crontab file in the var directory and it will be updated automatically (the temporary file will be automatically deleted).
Insert image description here

Let’s take a look at the execution effect of scheduled tasks:
Insert image description here
No problem.

Crontab has many practical application scenarios in Linux systems. The following are some common examples:

  1. Scheduled backup: You can use crontab to execute backup scripts regularly to protect important data. For example, execute a backup script every night to copy critical files to another location or remote server.

  2. Log cleaning: System logs and application logs can take up a lot of disk space. Use crontab to clean out outdated log files regularly to avoid low disk space issues.

  3. System maintenance tasks: crontab can be used to automate various system maintenance tasks, such as updating software packages, performing disk defragmentation, optimizing databases, etc.

  4. Data synchronization: If you have multiple servers that need data synchronization, you can use crontab to run data synchronization scripts regularly to ensure data consistency.

  5. Website monitoring: You can use crontab to regularly check the availability and response time of the website, as well as monitor the load of the server. This allows potential problems to be discovered and resolved in a timely manner.

  6. Scheduled task reminders: You can use crontab to create reminder tasks, such as sending an email or pop-up notification every morning to remind you of important tasks or events.

This is just a small sample of crontab applications. In fact, you can use crontab to perform various scheduled tasks according to your own needs and creativity, improve work efficiency and automate operations.



Write my love for you forever at the end of the poem ~

Guess you like

Origin blog.csdn.net/weixin_43764974/article/details/131015882
Recommended