/etc/cron.{hourly|daily|weekly|monthly} 的用法
2 min readMar 21, 2017
- 必須是可當執行檔用的內容,例如 shell script,且檔案全必須有 +x
- 如果是 shell script 的話,開頭的第一行要有 #!/bin/sh (或 #!/bin/bash)
來個範例
touch /etc/cron.daily/ntpdate
chmod +x /etc/cron.daily/ntpdate
vim /etc/cron.daily/ntpdate
內容:
#!/bin/sh
ntpdate ntp.ubuntu.com
裡面沒有特別 su 的話,就是以 root 身分執行。
我們打開 /etc/crontab 可以看到裡面有以下幾行
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
再找一下 run-parts 的用法,就會知道 /etc/cron.{hourly|daily|weekly|monthly} 是怎麼運作了。理解後,若想要自己弄個 minutly 的機制出來也不會太難。
設定完後若想要知道 run-parts 執行有沒有成功:
run-parts --test /etc/cron.daily# 顯示
/etc/cron.daily/apport
/etc/cron.daily/apt-compat
/etc/cron.daily/bsdmainutils
/etc/cron.daily/dpkg
/etc/cron.daily/logrotate
看一下自己的 script 有沒有出現在裡面就行了。
提醒: 檔名不要有 “.”,例如 “renew.sh”, “renew-cert-example.com”