◾️はじめに
cron / crontab に関するメモ
目次
【1】cron / crontab 1)cronコマンド 2)crontabコマンド 【2】/etc/cron.d と crontab の違い 【3】フォーマット 1)間隔設定 2)複数設定 3)範囲設定 【4】サンプル 例1:Hello World 例2:指定した日付(例:04/17(月) 00:00)でファイルを差し替える
【1】cron / crontab
1)cronコマンド
* クローン
/etc/cron.d
* 決められた時刻にコマンド/プログラム/シェルを 定期的に実行させるためのデーモン
2)crontabコマンド
* クローン タブ
/etc/crontab
* 一定の時間に自動で起動させるためのスケジューラを管理するコマンド
コマンド例
# 設定内容をエディタを起動して編集する crontab -u 【ユーザ名】 -e # 設定内容を表示する crontab -l # 設定内容を破棄 crontab -r
2)/etc/cron.d と crontab の違い
/etc/cron.d
* ユーザ問わず利用可能
crontab
* ユーザ毎にファイルがある
【3】フォーマット
分 時 日 月 曜日 ユーザ コマンド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 |
1)間隔設定
* 「/」の後に実行したい間隔の値を設定することで、 その間隔で実行することができる * 使用上の注意については、以下の関連記事を参照のこと。
https://dk521123.hatenablog.com/entry/2021/04/01/160946
2)複数設定
* 「,」
3)範囲設定
* 「-」
【4】サンプル
例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
関連記事
cron / crontab 〜 基本編 〜
https://dk521123.hatenablog.com/entry/2017/08/20/184005
cron / crontab 〜 あれこれ編 〜
https://dk521123.hatenablog.com/entry/2021/04/01/160946
コマンドの定期実行を考える
https://dk521123.hatenablog.com/entry/2017/12/31/000300
Python 〜 croniter 〜
https://dk521123.hatenablog.com/entry/2025/10/31/000250