centos cron_如何在CentOS 8上使用Cron自动化任务

本文介绍了如何在CentOS 8系统中安装和使用Cron来自动化任务。Cron是一个时间调度守护进程,适用于Unix-like操作系统。首先,你需要更新系统并安装cron守护程序。然后,通过编辑crontab文件来创建和管理计划任务。文章还涵盖了cron表达式的基本语法,用于定义任务的执行时间,并提供了示例。最后,讨论了如何管理和重定向cron作业的输出,以及如何通过限制访问来保护cron服务。
摘要由CSDN通过智能技术生成

centos cron

A previous version of this tutorial was written by Shaun Lewis.

本教程的先前版本由Shaun Lewis编写。

介绍 (Introduction)

Cron is a time-based job scheduling daemon found in Unix-like operating systems, including Linux distributions. Cron runs in the background and tasks scheduled with cron, referred to as “cron jobs,” are executed automatically, making cron useful for automating maintenance-related tasks.

Cron是一个基于时间的作业调度守护程序,可在类似Unix的操作系统(包括Linux发行版)中找到。 Cron在后台运行,并且按cron计划的任务(称为“ cron作业”)会自动执行,这使cron对于自动执行与维护相关的任务非常有用。

This guide provides an overview of how to schedule tasks using cron’s special syntax. It also goes over a few shortcuts one can use to make job schedules easier to write and understand.

本指南概述了如何使用cron的特殊语法安排任务。 它还介绍了一些捷径,可以使工作计划更易于编写和理解。

先决条件 (Prerequisites)

To complete this guide, you’ll need access to a computer running CentOS 8. This could be your local machine, a virtual machine, or a virtual private server.

要完成本指南,您需要访问运行CentOS 8的计算机。该计算机可以是本地计算机,虚拟机或虚拟专用服务器。

Regardless of what kind of computer you use to follow this guide, it should have a non-root user with administrative privileges configured. To set this up, follow our Initial Server Setup guide for CentOS 8.

无论您使用哪种计算机来遵循本指南,它都应该具有配置了管理特权的非root用户。 要进行设置,请遵循我们的CentOS 8初始服务器设置指南

安装Cron (Installing Cron)

Almost every Linux distribution has some form of cron installed by default. However, if you’re using a CentOS machine on which cron isn’t installed, you can install it using dnf.

默认情况下,几乎每个Linux发行版都安装了某种形式的cron。 但是,如果您使用的是未安装cron的CentOS计算机,则可以使用dnf进行安装。

Before installing cron on a CentOS machine, update the computer’s local package index:

在CentOS计算机上安装cron之前,请更新计算机的本地软件包索引:

  • sudo dnf update

    sudo dnf更新

Then install the cron daemon with the following command:

然后使用以下命令安装cron守护程序:

  • sudo dnf install crontabs

    sudo dnf安装crontabs

This command will prompt you to confirm that you want to install the crontabs package and its dependencies. Do so by pressing y then ENTER.

该命令将提示您确认要安装crontabs软件包及其依赖项。 依次按y ENTER

This will install cron on your system, but you’ll need to start the daemon manually. You’ll also need to make sure it’s set to run whenever the server boots. You can perform both of these actions with the systemctl command.

这将在您的系统上安装cron,但是您需要手动启动守护程序。 您还需要确保将其设置为在服务器启动时运行。 您可以使用systemctl命令执行这两个操作。

To start the cron daemon, run the following command:

要启动cron守护程序,请运行以下命令:

  • sudo systemctl start crond.service

    sudo systemctl启动crond.service

To set cron to run whenever the server starts up, type:

要将cron设置为在服务器启动时运行,请键入:

  • sudo systemctl enable crond.service

    sudo systemctl启用crond.service

Following that, cron will be installed on your system and ready for you to start scheduling jobs.

之后,将cron安装在您的系统上,并准备开始调度作业。

了解Cron的工作方式 (Understanding How Cron Works)

Cron jobs are recorded and managed in a special file known as a crontab. Each user profile on the system can have their own crontab where they can schedule jobs, which is stored under /var/spool/cron/.

Cron作业在称为crontab的特殊文件中记录和管理。 系统上的每个用户配置文件都可以具有自己的crontab,可以在其中计划作业,这些作业存储在/var/spool/cron/

To schedule a job, you just need to open up your crontab for editing and add a task written in the form of a cron expression. The syntax for cron expressions can be broken down into two elements: the schedule and the command to run.

要安排工作,您只需要打开crontab进行编辑并添加以cron表达式形式编写的任务。 cron表达式的语法可以分为两个元素:调度和要运行的命令。

The command can be virtually any command you would normally run on the command line. The schedule component of the syntax is broken down into 5 different fields, which are written in the following order:

该命令实际上可以是您通常在命令行上运行的任何命令。 语法的时间表组件分为5个不同的字段,按以下顺序编写:

FieldAllowed Values
minute0-59
hour0-23
Day of the month1-31
month1-12 or JAN-DEC
Day of the week0-6 or SUN-SAT
领域 允许值
分钟 0-59
小时 0-23
一个月中的某天 1-31
1-12JAN-DEC
一周中的天 0-6SUN-SAT

Together, tasks scheduled in a crontab are structured like this:

一起,在crontab中计划的任务的结构如下:

minute hour day_of_month month day_of_week command_to_run

Here’s a functional example of a cron expression. This expression runs the command curl http://www.google.com every Tuesday at 5:30 PM:

这是cron表达式的功能示例。 此表达式每个星期二下午5:30运行curl http://www.google.com命令:

30 17 * * 2 curl http://www.google.com

There are also a few special characters you can include in the schedule component of a cron expression to make scheduling easier:

您还可以在cron表达式的计划组件中包括一些特殊字符,以使计划更加容易:

  • *: In cron expressions, an asterisk is a wildcard variable that represents “all.” Thus, a task scheduled with * * * * * ... will run every minute of every hour of every day of every month.

    * :在cron表达式中,星号是表示“全部”的通配符变量。 因此,计划有* * * * * ...的任务将在每月的每一天的每一小时的每一分钟运行。

  • ,: Commas break up scheduling values to form a list. If you want to have a task run at the beginning and middle of every hour, rather than writing out two separate tasks (e.g., 0 * * * * ... and 30 * * * * ...), you could achieve the same functionality with one (0,30 * * * * ...).

    , ::分解调度值以形成列表。 如果您希望在每小时的开始和中间运行一个任务,而不是写出两个单独的任务(例如0 * * * * ...30 * * * * ... ),则可以实现具有相同的功能( 0,30 * * * * ... )。

  • -: A hyphen represents a range of values in the schedule field. Instead of having 30 separate scheduled tasks for a command you want to run for the first 30 minutes of every hour (as in 0 * * * * ..., 1 * * * * ..., 2 * * * * ..., and so on), you could just schedule it as 0-29 * * * * ....

    - :连字符表示日程表字段中的值范围。 您要在每小时的前30分钟内运行命令,而不是为命令分配30个单独的计划任务(如0 * * * * ...1 * * * * ...2 * * * * ...等),你可以只安排它为0-29 * * * * ...

  • /: You can use a forward slash with an asterisk to express a step value. For example, instead of writing out eight separate separate cron tasks to run a command every three hours (as in, 0 0 * * * ..., 0 3 * * * ..., 0 6 * * * ..., and so on), you could schedule it to run like this: 0 */3 * * * ....

    / :您可以使用带星号的正斜杠来表示步长值。 例如,与其写出八个独立的cron任务来每三个小时运行一个命令(例如0 0 * * * ...0 3 * * * ...0 6 * * * ... ,等等),您可以安排它像这样运行: 0 */3 * * * ...

Note: You cannot express step values arbitrarily; you can only use integers that divide evenly into the range allowed by the field in question. For instance, in the “hours” field you could only follow a forward slash with 1, 2, 3, 4, 6, 8, or 12.

注意 :您不能任意表达步长值; 您只能使用整数,该整数平均分配到相关字段所允许的范围内。 例如,在“时间”字段你只能跟随正斜杠用123468 ,或12

Here are some more examples of how to use cron’s scheduling component:

以下是一些更多有关如何使用cron的调度组件的示例:

  • * * * * * - Run the command every minute.

    * * * * * -每分钟运行一次命令。

  • 12 * * * * - Run the command 12 minutes after every hour.

    12 * * * * -每小时12分钟后运行命令。

  • 0,15,30,45 * * * * - Run the command every 15 minutes.

    0,15,30,45 * * * * -每15分钟运行一次命令。

  • */15 * * * * - Run the command every 15 minutes.

    */15 * * * * -每15分钟运行一次命令。

  • 0 4 * * * - Run the command every day at 4:00 AM.

    0 4 * * * -每天凌晨4:00运行命令。

  • 0 4 * * 2-4 - Run the command every Tuesday, Wednesday, and Thursday at 4:00 AM.

    0 4 * * 2-4在每个星期二,星期三和星期四的4:00 AM运行命令。

  • 20,40 */8 * 7-12 * - Run the command on the 20th and 40th minute of every 8th hour every day of the last 6 months of the year.

    20,40 */8 * 7-12 * -在一年的最后6个月中的每天的第8小时的第20和40分钟运行命令。

If you find any of this confusing or if you’d like help writing schedules for your own cron tasks, Cronitor provides a handy cron schedule expression editor named “Crontab Guru” which you can use to check whether your cron schedules are valid.

如果您发现任何令人困惑的地方,或者想要帮助您为自己的cron任务编写时间表, Cronitor都会提供一个方便的cron时间表表达式编辑器,名为“ Crontab Guru” ,可用于检查您的cron时间表是否有效。

管理Crontab (Managing Crontabs)

Once you’ve settled on a schedule and you know the job you want to run, you’ll need to put it somewhere your daemon will be able to read it.

一旦确定了时间表,并且知道要运行的作业,就需要将其放在守护程序能够读取的位置。

As mentioned previously, a crontab is a special file that holds the schedule of jobs cron will run. However, these are not intended to be edited directly. Instead, it’s recommended that you use the crontab command. This allows you to edit your user profile’s crontab without changing your privileges with sudo. The crontab command will also let you know if you have syntax errors in the crontab, while editing it directly will not.

如前所述,crontab是一个特殊文件,其中包含cron将运行的作业计划。 但是,这些内容不打算直接进行编辑。 相反,建议您使用crontab命令。 这使您可以编辑用户配置文件的crontab,而无需使用sudo更改特权。 crontab命令还将让您知道crontab是否存在语法错误,而直接编辑则不会。

You can edit your crontab with the following command:

您可以使用以下命令编辑crontab:

  • crontab -e

    crontab -e

This will open up your crontab in your user profile’s default text editor.

这将在用户个人资料的默认文本编辑器中打开crontab。

Note: On new CentOS 8 servers, the crontab -e command will open up your user’s crontab with vi by default. vi is an extremely powerful and flexible text editor, but it can feel somewhat obtuse for users who lack experience with it.

注意 :在新的CentOS 8服务器上,默认情况下, crontab -e命令将使用vi打开用户的crontab。 vi是一个功能强大且灵活的文本编辑器,但是对于缺乏使用经验的用户而言,它可能会感到有些呆板。

If you’d like to use a more approachable text editor as your default crontab editor, you could install and configure nano as such.

如果您想使用更易于接近的文本编辑器作为默认的crontab编辑器,则可以这样安装和配置nano

To do so, install nano with dnf:

为此,请使用dnf安装nano

  • sudo dnf install nano

    须藤dnf安装纳米

When prompted, press y and then ENTER to confirm that you want to install nano.

出现提示时,按y ,然后按ENTER以确认您要安装nano

To set nano as your user profile’s default visual editor, open up the .bash_profile file for editing. Now that you’ve installed it, you can do so with nano:

要将nano设置为用户配置文件的默认视觉编辑器,请打开.bash_profile文件进行编辑。 现在,您已经安装了它,您可以使用nano

  • nano ~/.bash_profile

    纳米〜/ .bash_profile

At the bottom of the file, add the following line:

在文件底部,添加以下行:

~/.bash_profile
〜/ .bash_profile
. . .
export VISUAL="nano"

This sets the VISUAL environment variable to nano. VISUAL is a Unix environment variable that many programs — including crontab — invoke to edit a file. After adding this line, save and close the file by pressing CTRL + X, Y, then ENTER.

这将VISUAL环境变量设置为nanoVISUAL是Unix环境变量,许多程序(包括crontab)都调用它来编辑文件。 添加此行之后,按CTRL + XY ,然后按ENTER ,保存并关闭文件。

Then reload .bash_profile so the shell picks up the new change:

然后重新加载.bash_profile以便外壳程序获取新的更改:

  • . ~/.bash_profile

    。 〜/ .bash_profile

Once in the editor, you can input your schedule with each job on a new line. Otherwise, you can save and close the crontab for now. If you opened your crontab with vi, the default CentOS 8 text editor, you can do so by pressing ESC to make sure you’re in vi’s command mode, then type :x and press ENTER.

进入编辑器后,您可以在新行中输入每个作业的时间表。 否则,您可以暂时保存并关闭crontab。 如果您使用默认的CentOS 8文本编辑器vi打开了crontab,则可以通过按ESC以确保您处于vi的命令模式下,然后键入:x并按ENTER

Please note that, on Linux systems, there is another crontab stored under the /etc/ directory. This is a system-wide crontab that has an additional field for which user profile each cron job should be run under. This tutorial focuses on user-specific crontabs, but if you wanted to edit the system-wide crontab, you could do so with the following command:

请注意,在Linux系统上,在/etc/目录下存储了另一个crontab。 这是系统级的crontab,具有一个附加字段,每个cron作业都应在其下运行用户配置文件。 本教程侧重于特定于用户的crontab,但是,如果要编辑系统范围的crontab,可以使用以下命令进行编辑:

  • sudo nano /etc/crontab

    须藤nano / etc / crontab

If you’d like to view the contents of your crontab, but not edit it, you can use the following command:

如果要查看crontab的内容但不对其进行编辑,则可以使用以下命令:

  • crontab -l

    crontab -l

You can erase your crontab with the following command:

您可以使用以下命令擦除crontab:

Warning: The following command will not ask you to confirm that you want to erase your crontab. Only run it if you are certain that you want to erase it.

警告 :以下命令不会要求您确认要删除crontab。 仅在确定要删除它时才运行它

  • crontab -r

    crontab -r

This command will delete the user’s crontab immediately. However, you can include the -i flag to have the command prompt you to confirm that you actually want to delete the user’s crontab:

此命令将立即删除用户的crontab。 但是,可以包含-i标志,以使命令提示您确认您确实要删除用户的crontab:

  • crontab -r -i

    crontab -r -i

   
   
Output
crontab: really delete sammy's crontab?

When prompted, you must enter y to delete the crontab or n to cancel the deletion.

出现提示时,必须输入y删除crontab或输入n取消删除。

管理Cron作业输出 (Managing Cron Job Output)

Because cron jobs are executed in the background, it isn’t always apparent that they’ve run successfully. Now that you know how to use the crontab command and how to schedule a cron job, you can start experimenting with some different ways of redirecting the output of cron jobs to help you track that they’ve been executed successfully.

由于cron作业是在后台执行的,因此不一定总是可以成功运行它们。 现在,您知道如何使用crontab命令以及如何计划cron作业,您可以开始尝试一些不同的方法来重定向cron作业的输出,以帮助您跟踪它们已成功执行。

If you have a mail transfer agent — such as Sendmail — installed and properly configured on your server, you can send the output of cron tasks to the email address associated with your Linux user profile. You can also manually specify an email address by providing a MAILTO setting at the top of the crontab.

如果您在服务器上安装并正确配置了邮件传输代理 (例如Sendmail) ,则可以将cron任务的输出发送到与Linux用户配置文件关联的电子邮件地址。 您还可以通过在crontab顶部提供MAILTO设置来手动指定电子邮件地址。

For example, you could add the following lines to a crontab. These include a MAILTO statement followed by an example email address, a SHELL directive that indicates the shell to run (bash in this example), a HOME directive pointing to the path in which to search for the cron binary, and a single cron task:

例如,您可以将以下几行添加到crontab中。 其中包括MAILTO语句,后跟示例电子邮件地址,指示要运行的shell的SHELL指令(在本示例中为bash ),指向搜索cron二进制文件的路径的HOME指令以及单个cron任务:

. . .

MAILTO="example@digitalocean.com"
SHELL=/bin/bash
HOME=/

* * * * * echo ‘Run this command every minute’

This particular job will return “Run this command every minute,” and that output will get emailed every minute to the email address specified after the MAILTO directive.

该特定作业将返回“每分钟运行此命令”,并且该输出将每分钟通过电子邮件发送到MAILTO指令之后指定的电子邮件地址。

You can also redirect a cron task’s output into a log file or into an empty location to prevent getting an email with the output.

您也可以将cron任务的输出重定向到日志文件或空白位置,以防止收到包含该输出的电子邮件。

To append a scheduled command’s output to a log file, add >> to the end of the command followed by the name and location of a log file of your choosing, like this:

要将预定命令的输出附加到日志文件,请在命令末尾添加>> ,然后添加您选择的日志文件的名称和位置,如下所示:

* * * * * echo ‘Run this command every minute’ >> /directory/path/file.log

Let’s say you want to use cron to run a script but keep it running in the background. To do so, you could redirect the script’s output to an empty location, like /dev/null which immediately deletes any data written to it. For example, the following cron job executes a PHP script and runs it in the background:

假设您要使用cron来运行脚本,但要使其在后台运行。 为此,您可以将脚本的输出重定向到一个空位置,例如/dev/null ,它会立即删除写入其中的所有数据。 例如,以下cron作业执行一个PHP脚本并在后台运行它:

* * * * * /usr/bin/php /var/www/domain.com/backup.php > /dev/null 2>&1

This cron job also redirects standard error — represented by 2 — to standard output (>&1). Because standard output is already being redirected to /dev/null, this essentially allows the script to run silently. Even if the crontab contains a MAILTO statement, the command’s output won’t be sent to the specified email address.

此cron作业还将标准错误 (由2表示)重定向到标准输出( >&1 )。 因为标准输出已经被重定向到/dev/null ,这实际上允许脚本静默运行。 即使crontab包含MAILTO语句,命令的输出也不会发送到指定的电子邮件地址。

限制访问 (Restricting Access)

You can manage which users are allowed to use the crontab command with the cron.allow and cron.deny files, both of which are stored in the /etc/ directory. If the cron.deny file exists, any user listed in it will be barred from editing their crontab. If cron.allow exists, only users listed in it will be able to edit their crontabs. If both files exist and the same user is listed in each, the cron.allow file will override cron.deny and the user will be able to edit their crontab.

您可以通过cron.allowcron.deny文件管理允许哪些用户使用crontab命令,这两个文件都存储在/etc/目录中。 如果cron.deny文件存在,则其中列出的所有用户都将被禁止编辑其crontab。 如果cron.allow存在,则只有其中列出的用户才能编辑其crontab。 如果两个文件都存在,并且每个文件中都列出了相同的用户,则cron.allow文件将覆盖cron.deny ,并且用户将能够编辑其crontab。

For example, to deny access to all users and then give access to the user ishmael, you could use the following command sequence:

例如,要拒绝对所有用户的访问,然后对用户ishmael授予访问权限,可以使用以下命令序列:

  • sudo echo ALL >>/etc/cron.deny

    sudo echo ALL >> / etc / cron.deny
  • sudo echo ishmael >>/etc/cron.allow

    须藤echo ishmael >> / etc / cron.allow

First, we lock out all users by appending ALL to the cron.deny file. Then, by appending the username to the cron.allow file, we give the ishmael user profile access to execute cron jobs.

首先,我们通过将ALL附加到cron.deny文件中来锁定所有用户。 然后,通过将用户名附加到cron.allow文件中,我们授予ishmael用户配置文件访问权限以执行cron作业。

Note that if a user has sudo privileges, they can edit another user’s crontab with the following command:

请注意,如果用户具有sudo特权,则可以使用以下命令来编辑另一个用户的crontab:

  • sudo crontab -u user -e

    sudo crontab -u 用户 -e

However, if cron.deny exists and user is listed in it and they aren’t listed in cron.allow, you’ll receive the following error after running the previous command:

但是,如果cron.deny存在并且其中列出了用户 ,而cron.allow中没有列出用户,则在运行上一个命令后会出现以下错误:


   
   
Output
The user user cannot use this program (crontab)

By default, most cron daemons will assume all users have access to cron unless either cron.allow or cron.deny exists.

默认情况下,除非存在cron.allowcron.deny否则大多数cron守护程序都将假定所有用户都可以访问cron。

特殊语法 (Special Syntax)

There are also several shorthand commands you can use in your crontab file to help streamline job scheduling. They are essentially shortcuts for the equivalent numeric schedule specified:

您还可以在crontab文件中使用一些速记命令来帮助简化作业计划。 它们本质上是指定的等效数字时间表的快捷方式:

ShortcutShorthand for
@hourly0 * * * *
@daily0 0 * * *
@weekly0 0 * * 0
@monthly0 0 1 * *
@yearly0 0 1 1 *
捷径 的简写
@hourly 0 * * * *
@daily 0 0 * * *
@weekly 0 0 * * 0
@monthly 0 0 1 * *
@yearly 0 0 1 1 *

Note: Not all cron daemons can parse this syntax (particularly older versions), so double-check it works before you rely on it.

注意 :并非所有cron守护程序都可以解析此语法(尤其是较旧的版本),因此在依赖它之前请仔细检查它是否有效。

Additionally, the @reboot shorthand will run whatever command follows it any time the server starts up:

此外, @reboot简写形式将在服务器@reboot时运行@reboot任何命令:

@reboot echo "System start up"

Using these shortcuts whenever possible can help make it easier to interpret the schedule of tasks in your crontab.

尽可能使用这些快捷方式可以帮助您更轻松地解释crontab中的任务计划。

结论 (Conclusion)

Cron is a flexible and powerful utility that can reduce the burden of many tasks associated with system administration. When combined with shell scripts, you can automate tasks that are normally tedious or complicated.

Cron是一种灵活而强大的实用程序,可以减轻与系统管理相关的许多任务的负担。 与shell脚本结合使用时,您可以使通常繁琐或复杂的任务自动化。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-cron-to-automate-tasks-centos-8

centos cron

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值