1
1

More than 3 years have passed since last update.

cron

Last updated at Posted at 2020-09-24

cron とは

cronとは、多くのUNIX系OSで標準的に利用される常駐プログラム(デーモン)の一種で、利用者の設定したスケジュールに従って指定されたプログラムを定期的に起動してくれるもの。
引用:IT用語辞典 e-Words

cron を起動(停止)する

cron を利用するにはデーモンを起動する必要があります。
$ sudo service cron start

停止
$ sudo service cron stop

起動確認
$ sudo service cron status

ファイルの配置

/etc/cron.d/ にある拡張子のないファイルが実行されます。

sudo vi /etc/cron.d/your-script

書式

[分] [時] [日] [月] [曜日][実行するユーザ][コマンド]

  • 分: 0~59
  • 時: 0~23
  • 日: 1~31
  • 月: 1~12
  • 曜日: 0 or 7 (日)、1 (月)、2 (火)、3 (水)、4 (木)、5 (金)、6 (土)
  • コマンド: PATH を通していないものは絶対パスか相対パスで指定

XX時YY分に実行

your-script
SHELL=/bin/bash
# 毎日 09:05 にスクリプトを実行
5 9 * * * ubuntu SCRIPT

X 分間隔で実行

your-script
SHELL=/bin/bash
# 1 分間隔でスクリプトを実行する
*/1 * * * * ubuntu SCRIPT

X 秒間隔で実行

書式の範囲では表記できません。最小単位が ”分” だから。

your-script
SHELL=/bin/bash
# 5 秒間隔でスクリプトを実行する
* * * * * ubuntu for i in `seq 0 5 59`;do (sleep ${i} ; SCRIPT) & done;
# 15 秒間隔でスクリプトを実行する
* * * * * ubuntu for i in `seq 0 15 59`;do (sleep ${i} ; SCRIPT) & done;

日時指定いろいろ

[分] [時] [日] [月] [曜日] 実行日時
5 10 * * * 10:05
0 9 * * * 9:00
0 9 * * 1 月曜日 9:00
0,30 9 * * 1,2 月・火曜日の 9:00 と 9:30
0-10 9 * * * 9:00 から 9:10 で 1 分間隔
0,10,20,30,40,50 * * * * 10 分間隔
*/10 * * * * 10 分間隔
* 9 * * * 9:00 から 9:59 まで 1 分間隔
0 * * * * 00 分に 1 時間間隔
15 1-12/2 * * * 1:15, 3:15, 5:15, 7:15, 9:15, 11:15

ログ設定 (デフォルト無効)

$ sudo vi /etc/rsyslog.d/50-default.conf

50-default.conf
- #cron.*   /var/log/cron.log
+ cron.*    /var/log/cron.log

sudo tree /etc/cron*

ubuntu:~$ sudo tree /etc/cron*
/etc/cron.d
├── e2scrub_all
└── popularity-contest
/etc/cron.daily
├── apport
├── apt-compat
├── bsdmainutils
├── dpkg
├── logrotate
├── man-db
├── popularity-contest
└── update-notifier-common
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly
├── man-db
└── update-notifier-common
/etc/crontab [error opening dir]

0 directories, 12 files

環境

ubuntu:~$ uname -a
Linux ubuntu 5.4.0-48-generic #52-Ubuntu SMP Thu Sep 10 10:58:49 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
ubuntu:~$ cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.1 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.1 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
1
1
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
1
1