# chap1 熟悉crontab ###### tags: `crontab` - edited:2020.02.05 --- - 相關文章可以參考[Crontab教學 - 總覽](https://hackmd.io/0UWA1D-LRTOkx-EH4xnWQA?edit) ## Intro - **Ubuntu18.04**內建crontab,開啟`Terminal`環境開始認識**crontab** ### 確認crontab服務有無開啟: `service --status-all` >- crontab有啟動的樣子 ``` [ + ] cron #<--- 有加號代表有啟動 [ - ] dbus [ ? ] hwclock.sh [ - ] procps [ - ] x11-common ``` >- crontab未啟動的樣子, 透過`service cron start`來啟動**crontab** ``` [ - ] cron #<--- 減號代表有未啟動 [ - ] dbus [ ? ] hwclock.sh [ - ] procps [ - ] x11-common ``` ### crontab 的格式 - 設定crontab的任務,格式如下: >- `min hour day month week [YOUR_TASK] [FILE_MODE YOUR_LOG_FILE_PATH]` - 建立一個簡單的任務`date > ~/Desktop/helloWorld.log`來了解crontab時間的設定,這個任務會將系統的時間輸出到`~/Desktop/helloWorld.log`。 - Example: 假設我現在時間是11:58分, 我設定一個任務在`11:59`執行, 用`*`在其他時間欄位代表**省略** >- `59 12 * * * date > ~/Desktop/helloWorld.log` >- 此時, 若`~/Desktop/helloWorld.log`檔案存在,開啟裡面的資料顯示**當下的日期+任務執行的時間**,代表成功囉. - 相關的設定方式如下表: -  - 以下為crontab時間設定的一些範例: | 時間格式 | 說明 | | -------- | -------- | | `*/2 * * * *` | 每兩小時跑一次任務 | | `0 23-7/2,8 * * * date ` | 11:00 p.m ~ 7:00 a.m 每兩小時執行一次任務, 8:00a.m 也執行一次 | | `01 00 1 1 *` | 1月1日的 00:01執行一次任務 | | `0 4 1 jan * date` | 每兩小時跑一次任務 | | ` 0 11 4 * mon-wed date ` | 每月的4號的11:00, 及星期一到星期三的11:00執行一次任務 | ## crontab 基本操作 - 在terminal模式底下,使用crontab的指令 | 指令 | 說明 | | -------- | -------- | | crontab -l | 列出crontab任務清單 | | crontab -e | 編輯crontab任務清單 | | crontab -r | 刪除crontab任務 | | crontab -i | 刪除crontab任務清單 | ## Reference - [crontab 使用格式說明](http://163.28.10.78/content/primary/info_edu/cy_sa/LinuxY/cmd/crontab.htm) - [Cron time string format ](https://support.acquia.com/hc/en-us/articles/360004224494-Cron-time-string-format) - [How To Start/Stop/Restart Cron Service In Linux](http://www.lifelinux.com/how-to-startstoprestart-cron-service-in-linux/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up