【1】cronコマンド
* クローン
/etc/cron.d
* 決められた時刻にコマンド/プログラム/シェルを 定期的に実行させるためのデーモン
/etc/cron.d配下の設定ファイルに関する注意点
[1] パーミッションは644にする => 「sudo chmod 0644 /etc/cron.d/xxxxx」を実行する [2] 所有者はrootにする => 「sudo chown root:root /etc/cron.d/xxxxx」を実行する
【2】crontab
* クローン タブ
/etc/crontab
* 一定の時間に自動で起動させるためのスケジューラを管理するコマンド
コマンド例
# 設定内容をエディタを起動して編集する crontab -u 【ユーザ名】 -e # 設定内容を表示する crontab -l # 設定内容を破棄 crontab -r
注意
「crontab -e」と「sudo crontab -e」は異なる 「crontab -e」は、実行ユーザ。 「sudo crontab -e」は、rootユーザ。
【3】/etc/cron.d と crontab の違い
/etc/cron.d
* ユーザ問わず利用可能
crontab
* ユーザ毎にファイルがある
注意
# /etc/cron.d の場合、ユーザ(以下の例だと「root」)を記述しておく必要がある */15 * * * * root ~/hello.sh
参考文献
https://qiita.com/calcabrina/items/6b6f24bb6169edf209c2
【4】ファイル書式
分 時 日 月 曜日 ユーザ コマンド1
http://www.k4.dion.ne.jp/~mms/unix/linux_com/crontab.html
# | 時間 | 範囲 | ワイルドカード(*)を指定した場合 | 備考 |
---|---|---|---|---|
1 | 分 | 0-59 | 毎分 | - |
2 | 時 | 0-23 | 毎時 | - |
3 | 日 | 1-31 | 毎日 | - |
4 | 月 | 1-12/jan-dec | 毎月 | - |
5 | 曜日 | 0-7/sun-sat | 毎日 | 0, 7は日曜日/sun,mon,tue,wed,thu,fri,sat |
間隔設定
* 「/」の後に実行したい間隔の値を設定することで、 その間隔で実行することができる * 使用上の注意については、以下の関連記事を参照のこと。
https://dk521123.hatenablog.com/entry/2021/04/01/160946
複数設定
* 「,」
範囲設定
* 「-」
【5】サンプル
例1:Hello World的なものをやってみる
hello.sh
#!/bin/sh date >> world.txt 「crontab -e」で、以下を記述し保存(毎分1分間隔で「world.txt」に日付が追記されていく) */1 * * * * ~/hello.sh
例2:指定した日付(例:04/17(月) 00:00)でファイルを差し替える
ディレクトリ構成例
home + user01 + index.html.for-20170417 (04/17(月) 00:00に展開したいindex.html) var + www + html + index.html (index.html)
deploy-for-20170417.sh
#!/bin/sh # 念のために、差し替えるファイルをバックアップ NOW=`date "+%Y%m%d%H%M%S"` cp /var/www/html/index.html /var/www/html/index.html.bk-${NOW} # ファイルを差し替える cp /home/user01/index.html.for-20170417 /var/www/html/index.html
コマンド例
「crontab -e」で、以下を記述し保存(2017/04/17(月) 00:00に差し替えられる) 0 0 17 4 mon /home/user01/deploy-for-20170417.sh
【6】cron あれこれ
1)viを指定する
http://blog.dacelo.info/linux/entry-939.html
EDITOR=vi export EDITOR
2)時間をランダムにずらして実行する
【例】毎日午前4時の0~60分(= 60 x 60[秒] = 3600[秒])の間に 【実行したいコマンド】 を実行する 0 4 * * * sleep `expr $RANDOM \% 3600`; 【実行したいコマンド】
参考文献
http://za.toypark.in/html/2006/05-28.html
http://uguisu.skr.jp/Windows/crontab.html
http://tips.recatnap.info/wiki/Cron%E3%82%92%E6%8C%87%E5%AE%9A%E6%99%82%E9%96%93%E3%81%AE%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E3%81%A7n%E7%A7%92%E5%BE%8C%E3%81%AB%E5%AE%9F%E8%A1%8C
3)特定の時間を除外する
【例】5分ごとに実行を。ただし、3時は除く。
# 「,」「-」を駆使して、指定する */5 0-2,4-23 * * * ~/hello.sh
参考文献
https://hacknote.jp/archives/29685/
【7】補足
* レンタルサーバーでは、GUIで対応しているところもあるらしい
lolipop
https://lolipop.jp/manual/user/cron/
参考文献
http://www.server-memo.net/tips/crontab.html
http://qiita.com/hikouki/items/e744b3a4d356d2af12cf
http://www.itsenka.com/contents/development/unix-linux/crontab.html
http://www.server-memo.net/tips/etc-crontab.html
関連記事
Cron がうまくいかなかった時の対処
https://dk521123.hatenablog.com/entry/2017/08/20/184005
Cron に関する使用上の注意
https://dk521123.hatenablog.com/entry/2021/04/01/160946
コマンドの定期実行を考える
https://dk521123.hatenablog.com/entry/2017/12/31/000300