0%

Linux下使用crontab创建定时任务

  1. 安装
  2. 添加定时任务
  3. 查看已创建的任务

安装

1
apt-get install cron

cron包括两部分,其中crond是一个守护进程,负责周期性的执行用户指定的任务。而crontab是一个用户级别的工具,用户可以通过crontab来编写各种任务

添加定时任务

进入编辑界面:crontab -e

定时任务格式:m h dom mon dow command

  • m 分钟 0-59
  • h 小时 0-23
  • dom 天 1-31
  • mon 月 1-12
  • dow 周 0-6(0是周日)
  • command 命令

示例:

1
2
3
4
* * * * * date >> time.log  # 每分钟记录时间
*/2 * * * * date >> time.log # 每隔2分钟记录时间
5 * * * * date >> time.log # 每小时的第5分钟
5,7 * * * * date >> time.log # 每小时的第5和7分钟

查看已创建的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$ crontab -l
# 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
10 0 * * * sh -c "a.sh"
10 0 * * * sh -c "b.sh"