> For the complete documentation index, see [llms.txt](https://lack.gitbook.io/operation-and-maintenance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lack.gitbook.io/operation-and-maintenance/yun-ji-suan/linuxren-wu-ji-hua.md).

# linux任务计划

基于crond服务 ：

crontab 命令：

介绍：设置linux的任务计划

格式：crontab \[option]

用法：

* -u ：指定用户，默认为当前用户
* -r ：删除计划任务
* -l ：查看当前计划
* -e : 编写计划任务(默认保存在/var/spool/cron/目录下的用户名文件中)

```bash
[root@localhost ~]# cat /etc/crontab # 配置文件
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
[root@localhost ~]# crontab -l
```

`crontab -l` 实际上是用vi打开了 `/var/spool/cron/username` 文件

> 命令错误 crond没启动或格式错误等都会造成计划任务不执行

```bash
[root@localhost ~]# crontab -l
# 每日8:15分给1.txt追加1
15 8 * * * echo "1" >> 1.txt

# 每隔8小时执行
* */8 * * * echo "1" >> 1.txt 2>>2.txt

# 每天的1,12,18时执行
* 1,12,18 * * * echo "1" >> 1.txt

# 每天的9:30到18:30执行
* 9-19 * * * echo "123" >> 1.txt

# 每周日的5:00执行
* 5 * * 0 echo "123" >> 1.txt
```

* 分范围0-59，时范围0-23，日范围1-31，月范围1-12，周1-7
* 可用格式1-5表示一个范围1到5
* 可用格式1,2,3表示1或者2或者3
* 可用格式\*/2表示被2整除的数字，比如小时，那就是每隔2小时

> 要保证服务是启动状态 `systemctl start crond.service`
