0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

crontab を有効にする手順(Amazon Linux 2023)

0
Posted at

そもそもcrontabとは何か?

Linuxで定期的にタスクを自動実行するための仕組み。

なぜcrontabを使用したのか?

AWS の EC2 を再起動した際に、手動でコマンドを実行することなく、
サービスを自動的に起動させるために crontab を使用しました。

手順

① cronie をインストール

sudo dnf install cronie -y

② crond サービスを起動 & 自動起動を設定

sudo systemctl enable crond sudo systemctl start crond

③ 再度 crontab 編集

crontab -e

これで編集画面が開けるようになります。

@reboot の設定例

# 該当のディレクトリに移動してEC2 起動時に Docker Compose を自動起動する設定
@reboot cd /home/ec2-user/hoge && docker compose -f docker-compose.yml up --build -d

crontab コマンド集

1. crontab の基本操作

crontab を編集する

crontab -e

現在の設定を確認する

crontab -l

crontab を削除する(⚠注意)

crontab -r

2. crontab の書式

分 時 日 月 曜日 コマンド

※曜日の指定

意味
0 または 7 日曜日
1 月曜日
2 火曜日
3 水曜日
4 木曜日
5 金曜日
6 土曜日

3. よく使う時間指定パターン

毎分実行

* * * * * コマンド

毎時 0 分に実行

0 * * * * コマンド

毎日 3:00 に実行

0 3 * * * コマンド

毎週月曜 9:00 に実行

0 9 * * 1 コマンド

毎月 1 日 0:00 に実行

0 0 1 * * コマンド

4. 間隔指定(/ の使い方)

5 分ごとに実行

*/5 * * * * コマンド

10 分ごとに実行

*/10 * * * * コマンド

2 時間ごとに実行

0 */2 * * * コマンド

5. 特殊指定(@ 系)

起動時に 1 回だけ実行
@reboot コマンド

毎日実行
@daily コマンド

毎週実行
@weekly コマンド

毎月実行
@monthly コマンド

まとめ

•	crontab は 定期実行・起動時実行 に使う
•	書式は「分 時 日 月 曜日」
•	@reboot は EC2 再起動時の自動処理に便利

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?