首页·终端命令

crontab

进程与系统

用法

crontab -e | crontab -l

管理每个用户的定时任务表;cron 运行时 PATH 几乎是空的,也不会读登录配置,所以路径要写绝对路径,而 `crontab -r` 会不问一声删掉整张表。

常用选项

选项含义
-eEdit your table in $EDITOR; it is installed when you save.
-lPrint your table. Redirect it somewhere to keep a backup.
-rDelete the whole table at once, with no confirmation.
-u <user>Work on another user's table (root only).
m h dom mon dowThe five time fields, then the command. * means every.
@reboot / @dailyShorthand instead of the five fields.

示例

crontab -l > ~/cron.bak

Back up the table before touching it.

crontab -e

Then add: 0 3 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

crontab -l | grep -v backup.sh | crontab -

Remove one line without opening an editor.

看什么在跑、什么在吃机器。先弄清是什么,再决定杀不杀。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. crontab 是做什么的?

管理每个用户的定时任务表;cron 运行时 PATH 几乎是空的,也不会读登录配置,所以路径要写绝对路径,而 `crontab -r` 会不问一声删掉整张表。

Q. 怎么写?

crontab -e | crontab -l —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 6 个,完整列表在 man crontab。这条命令属于进程与系统。

相关命令

man 手册: man crontab