# Crontab &amp; At

> 

Published: 2005-01-19
URL: https://kaochenlong.com/crontab-and-at

---

在Linux系統，`crontab` 跟 `at` 都是可以用來做排程，但這兩者的差異是：

- at：工作僅執行一次後就會系統中的排程中取消，工作排程會寫入到 `/var/spool/at` 目錄下。
- crontab：工作將持續例行性的執行，工作排程會寫入 `/var/spool/cron`。

`at` 的使用方法：

	&gt; at TIME

如果使用 `-m` 參數，`at` 會把排程輸出的結果 mail 給下達指令的使用者。

	&gt; at 5am
	warning: commands will be executed using (in order) a) $SHELL b) login shell c) /bin/sh

	at&gt; mail eddie -s “hi, eddie”

按下 `Ctrl+D` 就可離開 `at` 環境

	job １ at 2005-01-19 05:00

使用 `atq` 可看目前的at排程

	&gt; atq
	1　2005-01-19 05:00 a root

其中第一個 1 代表這個排程的編號

使用 `atm` 指令可移除已排好的工作

	&gt; atm 1

接下來介紹crontab的用法：

	&gt; crontab [-u user] [-l | -e | -r]
	-u user ：只有 root可使用，可以編譯其他使用者的crontab內容。
	-l：列出 crontab 內容。
	-e：編輯 crontab 內容。
	-r：刪除 crontab 內容。

執行 `crontab -e` 之後，則會進入一般的文字編輯器畫面編輯。

時間部份有5個欄位，分別是「分」、「時」、「日」、「月」、「星期幾」，最後就是要執行的工作，例如：

	0 12 * * * mail eddie -s test

就是在每個月的每天的12點0分時，寄一封主旨為 test 的信件給eddie。其中，「`*`」代表所有數字。星期幾這欄數值由0~6，0代表星期日。再看一個例子：

	*/5 * * * * mail eddie -s test

其中「`*/5`」表示每5分鐘寄一次信。

另外要注意的是，如果只是要刪除某個 crontab 的工作項目，建議使 `crontab -e` 來編輯，因為使用 `-r` 參數，會將所有的工作都移除。

如果是系統的例行性工作，不需要以某人的權限執行，則可編輯 `/etc/crontab` 檔案，詳細的內容在 `/etc/crontab` 檔案裡面有說明。

