个人工具

UbuntuHelp:CronHowto/zh

来自Ubuntu中文

(重定向自CronHowto
跳转至: 导航, 搜索

什么是Cron?

Cron是一个[守护程序]用于在指定的时间内执行行程类的任务,每一个用户都有一个 crontab 文件,来允许他们指定需要执行的内容和时间,此外,系统也有一个 crontab ,用来允许像交替日志和更新本地数据这样有规则的任务。

使用 Cron

使用 Cron, 只要在 crontab 文件中添加一些项目,一个 crontab 项目详细说明执行的过程和时间,如:

5 3 * * * /usr/bin/apt-get update

在crontab 项目里的第一个部分描述了执行任务的时间。它用空格分开成五个区域,每个只能用数字、“*”、或适当的字。这个区域依次说明 “分”,“时”,“每月几日”、“月”、“每周星期几”,月和星期可以用缩写,如 “jan"代替“January" 、"thu" 代替"Thursday"。

上面的例子将在每天的03:05执行“/usr/bin/apt-get update”(cron采用24小时制)

你要让cron在所有工作日中每5分钟显示干扰的消息,(上午9点到下午5点)请用

*/5 9-17 * * mon,tue,wed,thur,fri wall "Are we there yet?"

或者想使你想起一个生日,在每年正月十日的上午9点,用:

0 9 10 jan * echo "It's your mother's birthday today!" > ~/readme

查看 crontab 文件当今的内容,输入:

crontab -l

要使用系统环境默认的编辑器(一般是指vim)更改这个文件,输入: To edit the file, with the editor specified in your environment (which defaults to vim - :q! is the command to escape without saving if you get stuck and need to read up on it or change your editor), use:

crontab -e

ps: vim中使用命令“:q!”退出且不保存文件。如果你在编辑这个文件时遇到了麻烦需要重新读取这个文件或是想换一个编辑器,就可以输入这个命令。

当你关闭编辑器后,新的 crontab 文件将被安装上。用 crontab 命令编辑的文件保存在/var/spool/cron/crontabs

更多的内容

下面的命令保存 crontab 文件需要你的用户有要许可。如果你想要定期运行更大权限的命令, 请设置根 crontab 文件:

sudo crontab -e

取决于要运行的命令,你可能需要扩大根用户的 PATH 变量,请在他们的 crontab 文件的顶部输入下面的内容:

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

你最好先测试一下你将要采用的cron任务。一种办法是是设定任务在几分钟内运行,这就提前可以知道任务的结果。你也可以写一些命令到脚本里,以便记录其成功或失败,如下

echo "Nightly Backup Successful: $(date)" >> /tmp/mybackup.log

For more information, see the man pages for cron and crontab (man is detailed on the BasicCommands page). If your machine is regularly switched off, you may also be interest in at (part of the Ubuntu base install) and anacron (found in the Universe repository) that provide other approaches to scheduled tasks. For example, anacron offers simple system-wide directories for running commands hourly, daily, weekly, and monthly. Scripts to be executed in said times can be placed in /etc/cron.hourly/, /etc/cron.daily/, /etc/cron.weekly/, and /etc/cron.monthly/. All scripts in each directory are run as root, and a specific order to running the scripts can be specified by prefixing the scripts' file names with numbers (see the man page for run-parts for more details).

FIXME 翻译以上部分和以下部分

提示

crontab -e 使用编辑器环境的可变性。通过恰当的设置,使编辑器具有你自己的风格。你想要设置基于你自己的编辑器。ba shrc 因为许多命令使用可变性,让我们设置nano 一个使用简单的编辑器。

export EDITOR=nano

也有你能够为系统广义cron工作编辑的文件。大部分常见的文件位于“/etc/crontab“,而且这些文件的语法跟普通的aroncab的文件有细微的不同。

minute(s) hour(s) day(s)_of_month month(s) day(s)_of_week user command

It is recommended, however, that you try to avoid using /etc/crontab unless you need the flexibility offered by it, or if you'd like to create your own simplified anacron-like system using run-parts for example. For all cron jobs that you want to have run under your own user account, you should stick with using crontab -e to edit your local cron jobs rather than editting the system-wide /etc/crontab.