# Linux-Crontab命令

***

## 简介

crontab是用来设置定时执行语句或程序的指令。

直接使用crontab命令将读取一个文件（时程表），并将根据该文件的内容设置定时执行指令。

## 使用命令

```
crontab [ -u user ] file
```

> 指定时刻表

或

```
crontab [ -u user ] { -l | -r | -e }
```

> -e 指定编辑器 -r 移除当前时刻表 -l 列出当前时刻表

## 时间格式

时程表文件中设置定时执行任务的格式。

```
f1 f2 f3 f4 f5 program
```

解释：

> ```
> *    *    *    *    *
> -    -    -    -    -
> |    |    |    |    |
> |    |    |    |    +----- 星期中星期几 (0 - 6) (星期天 为0)
> |    |    |    +---------- 月份 (1 - 12) 
> |    |    +--------------- 一个月中的第几天 (1 - 31)
> |    +-------------------- 小时 (0 - 23)
> +------------------------- 分钟 (0 - 59)
> ```

* 中 f1 是表示分钟，f2 表示小时，f3 表示一个月份中的第几日，f4 表示月份，f5 表示一个星期中的第几天。program 表示要执行的程序。
* 当 f1 为 \* 时表示每分钟都要执行 program，f2 为 \* 时表示每小时都要执行程序，其馀类推
* 当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行，f2 为 a-b 时表示从第 a 到第 b 小时都要执行，其馀类推
* 当 f1 为 \*/n 时表示每 n 分钟个时间间隔执行一次，f2 为 \*/n 表示每 n 小时个时间间隔执行一次，其馀类推
* 当 f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行，f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行，其馀类推

## 例子

首先创建时程表文件

`vim timetable`

然后输入以下内容

```
0 */2 * * * touch /test/testfile 意思是每两个小时创建一个testfile 

50 7 * * * /sbin/service sshd start  意思是每天7：50开启ssh服务 

50 22 * * * /sbin/service sshd stop  意思是每天22：50关闭ssh服务 

0 0 1,15 * * fsck /home  每月1号和15号检查/home 磁盘 

1 * * * * /home/bruce/backup  每小时的第一分执行 /home/bruce/backup这个文件 

00 03 * * 1-5 find /home "*.xxx" -mtime +4 -exec rm {} \;  每周一至周五3点钟，在目录/home中，查找文件名为*.xxx的文件，并删除4天前的文件。

30 6 */10 * * ls  意思是每月的1、11、21、31日是的6：30执行一次ls命令
```

保存，输入`crontab timetable` 即可开启定时任务

输入`crontab -l`查看开启的定时任务

## 注意事项

* crontab 由 crond 服务调度，系统的 crond 服务每分钟会检查一次是否有需要执行的定时任务。因此任务执行的具体时间与添加 crontab 的时间无关。
* 由于定时任务是由系统服务执行的，所以不会弹出shell界面，因此在定时任务执行 echo 之类的命令没有意义。定时任务常用来设置简单的备份之类。
* 因为是系统服务执行，所以使用到的目录必须是绝对目录。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.mcyou.cc/hou-duan-xiang-guan/linux-crontab.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
