com.vix.cron_如何在Ubuntu 18.04上使用Cron自动化任务

news/2024/7/4 14:59:43

com.vix.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 Ubuntu 18.04. This could be your local machine, a virtual machine, or a virtual private server.

要完成本指南,您需要访问运行Ubuntu 18.04的计算机。 这可能是您的本地计算机,虚拟机或虚拟专用服务器。

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 Ubuntu 18.04.

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

安装Cron (Installing Cron)

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

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

Before installing cron on an Ubuntu machine, update the computer’s local package index:

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

  • sudo apt update

    sudo apt更新

Then install cron with the following command:

然后使用以下命令安装cron:

  • sudo apt install cron

    sudo apt安装cron

You’ll need to make sure it’s set to run in the background too:

您还需要确保它也设置为在后台运行:

  • sudo systemctl enable cron

    sudo systemctl启用cron

   
Output
Synchronizing state of cron.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable cron

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/crontabs/.

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

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

If this is the first time you’re running the crontab command under this user profile, it will prompt you to select a default text editor to use when editing your crontab:

如果这是您第一次在此用户配置文件下运行crontab命令,它将提示您选择在编辑crontab时要使用的默认文本编辑器:


   
Output
no crontab for sammy - using an empty one Select an editor. To change later, run 'select-editor'. 1. /bin/nano <---- easiest 2. /usr/bin/vim.basic 3. /usr/bin/vim.tiny 4. /bin/ed Choose 1-4 [1]:

Enter the number corresponding to the editor of your choice. Alternatively, you could just press ENTER to accept the default choice, nano.

输入与您选择的编辑器相对应的数字。 或者,您可以按ENTER接受默认选项nano

After making your selection, you’ll be taken to a new crontab containing some commented-out instructions on how to use it:

做出选择之后,您将被带到一个新的crontab,其中包含一些有关如何使用它的注释掉的说明:

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

When you run crontab -e in the future, it will bring up your crontab in this text editor automatically. 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 (CTRL + X, Y, then ENTER if you selected nano).

将来在运行crontab -e时,它将自动在此文本编辑器中显示crontab。 进入编辑器后,您可以在新行中输入每个作业的时间表。 否则,您可以暂时保存并关闭crontab( CTRL + XY ,如果选择nano ENTER )。

Note: 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? (y/n)

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. For instance, you could write a shell script to send data backups to an object storage solution and then automate it with cron.

Cron是一种灵活而强大的实用程序,可以减轻与系统管理相关的许多任务的负担。 与shell脚本结合使用时,您可以使通常繁琐或复杂的任务自动化。 例如,您可以编写一个Shell脚本以将数据备份发送到对象存储解决方案,然后使用cron将其自动化 。

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

com.vix.cron


http://www.niftyadmin.cn/n/3648870.html

相关文章

自定义TextView——解决ViewGroup不调用OnDraw方法

首先绘制TextView继承于View:直接贴代码 public class TextView extends LinearLayout{private String mText;private int mTextSize 18;private int mTextColor Color.BLACK;private Paint mPaint;//文字的画笔// 构造函数会在代码里面new的时候调用// TextView tv new Te…

Android Material Design-Maintaining Compatibility(保持兼容性)

一些materialdesign中的功能像material主题和自定义activity的过渡只能在Android 5.0(API级别21)或以上的系统版本中才能使用。但是你可以设计你的app去使用那些功能&#xff0c;无论在支持materialdesign的设备上亦或是早期的Android版本上。 定义可选的样式 你可以配置你的ap…

[Regex]Greta不支持“Named Groups”特性

微软研究院出品的Greta&#xff08;http://research.microsoft.com/projects/greta/&#xff09;是一款非常优秀的正则表达式模板类库&#xff0c;GRETA的匹配速度比boost(http://www.boost.org)正则表达式库大约快7倍&#xff0c;比ATL7的CATLRegExp快10倍。你可以通过http://…

盖茨比乔布斯_在盖茨比中使用React Hooks

盖茨比乔布斯JavaScript treats functions as first-class citizens. And we can see this in React now more than ever with the introduction of Hooks in version 16.8. They allow for state manipulation and side-effects on functional components. JavaScript将函数视…

android热修复——自己做个热修复

类的加载机制 需要注意的地方 1.每次生成之后一定要测试&#xff1b;2.尽量的不要分包&#xff0c;不要分多个dex3.混淆的时候&#xff0c;设计到NDK AndFix.java 不要混淆4.生成包之后一般会加固什么的&#xff0c;这个时候生成的差分包&#xff0c;一定要在之前去生成。5.…

Android系统权限配置详解

Android 权限控制代码分析 前在文章介绍过android系统管理层次&#xff1a;http://blog.csdn.net/andyhuabing/article/details/7030212 &#xff0c;这里就核心代码分析一下 android系统充分利用了linux的用户权限管理方法&#xff0c;所以如果需要移植到其它系统&#xff0c…

自己动手搭建数据库框架

首先IDaoSupport接口&#xff0c;有查询&#xff0c;插入单条数据&#xff0c;批量插入&#xff0c;删除&#xff0c;更新 public interface IDaoSupport<T> {void init(SQLiteDatabase sqLiteDatabase, Class<T> clazz);// 插入数据public long insert(T t);// 批…

关于软件的架构设计

好的开始相当于成功一半 开始之初的架构设计决定着软件产品的生死存亡。“好的开始相当于成功一半”。 开始的架构设计也是最难的&#xff0c;需要调研同类产品的情况以及技术特征&#xff0c;了解当前世界上对这种产品所能提供的理论支持和技术平台支持。再结合自己项目的特点…