linuxのサーバでcronでコマンドを定期実行する
- cron は決められた時間にコマンドを実行するデーモン(Unix系のOSで、主にバックグラウンドで動作するプロセス)
- ユーザーが直接コマンドをプロンプトに入力しなくても希望の時間に特定のコマンドを実行するための仕組み
- cronはデーモンとしてシステム起動時に立ち上がる
/etc/crontab
./etc/cron.d/*
,/var/spool/crontab/*
のcron job
と呼ぶコマンドを羅列したファイルを読み込み指定された時間に実行する
$ vim /etc/crontab SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed
$ ll /etc/cron.d -rw-r--r-- 1 root root 113 Sep 29 2016 0hourly -rw-r--r-- 1 root root 108 Sep 18 2014 raid-check -rw-r--r-- 1 root root 176 Nov 1 2014 update-motd
* cronのプロセスは以下で確認
$ ps ax | grep cro[n] 2647 ? Ss 0:00 crond
For CentOS
$ service crond status crond (pid 2647) is running...
For Ubuntu
$ service cron status
毎日深夜AM4:00にrootユーザでunix コマンドを実行する場合は以下の2つの方法どちらかで設定できる
$ sudo vim /etc/crontab
SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO=root HOME=/ # For details see man 4 crontabs # Example of job definition: # .---------------- minute (0 - 59) # | .------------- hour (0 - 23) # | | .---------- day of month (1 - 31) # | | | .------- month (1 - 12) OR jan,feb,mar,apr ... # | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat # | | | | | # * * * * * user-name command to be executed 0 4 * * * root touch /hoge.md
OR
$ sudo su root # crontab -l no crontab for root # crontab -e
0 4 * * * touch /hoge.md
$ crontab -l 0 4 * * * touch /hoge.md