# CRONTAB 排程工作

在 Linux 系統中，cron 是一種將工作排程的方式，關於 cron 的敘述，可以參考鳥哥的介紹: <http://linux.vbird.org/linux_basic/0430cron.php>

而在 OpenWRT 中也支援 cron 的功能，要啟用 cron 的功能，我們要先編輯 cron 的排程列表，輸入 `crontab -e`, 就可以開始編輯 cron 的工作排程，其格式如下:

![來自: http://einverne.github.io/post/2017/03/auto-reboot-openwrt.html](/files/-LXJTf8mmUT8LOaxZAj4)

簡單來說，就是定義: 分; 時; 日; 月; 周期 以及要執行的工作，舉例而言，我們可以定義:

```
*/1 * * * * echo "hello"
```

這樣就會每一分鐘都顯示一次 "hello" 訊息，我們可以在 logread 中看到:

```
root@OpenWrt:~# logread
Jun 21 07:17:01 OpenWrt cron.err crond[1211]: USER root pid 1495 cmd echo "hello"
```

當然，cron 用於 WiFi AP 主要是希望能夠提供管理上的功能，舉例來說，我們可以設定每天半夜定期重開機:

```
# Reboot at 0:45am every day
# Note: To avoid infinite reboot loop, wait 70 seconds
# and touch a file in /etc so clock will be set
# properly to 0:46 on reboot before cron starts.
45 0 * * * sleep 70 && touch /etc/banner && reboot
```

設定完 crontab 之後，要記得透過`/etc/init.d/cron start`開啟 OpenWRT 中 cron 的功能 (預設是關閉)，然而，此設定將隨重開機而消失，因此，可以修改開機進程(`/etc/rc.local`)，確保開機時啟動 cron。修改時，在`exit 0`前加入:

```
# start the cron service
/etc/init.d/cron enable
/etc/init.d/cron start
```

&#x20;這樣一來，就可以透過 logread 看到每天重開機，加上調整時間的成果，如下所示:&#x20;

```
Jan  1 08:01:21 OpenWrt daemon.info dnsmasq[1253]: using local addresses only for domain lan
Jun 21 00:48:23 OpenWrt cron.err crond[1212]: time disparity of 25491887 minutes detected
```

如果需要 OpenWRT 上更多關於 cron 的細節可以參考: <https://wiki.openwrt.org/doc/howto/cron>


---

# 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://openwrt-nctu.gitbook.io/project/openwrt-functions/openwrt-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.
