LoginSignup
19
24

More than 3 years have passed since last update.

ある日突然cronの設定を行った

Last updated at Posted at 2017-08-18

概要

サーバーのシャットダウンを忘れることがあるため、シャットダウンをするためのcronを設定してほしいとのことだった。:frowning2:
環境:centos 6.5

cronとは

指定時間や時間毎(1時間単位など)にプログラムを実行することができる。
crontabコマンドで設定する方法と /etc/cron.d/ 配下に設定ファイルを配置して設定する方法がある。
crontabで設定する場合、 crontab -e で設定を書いて、crontab -lで設定一覧を見ることができる。
crontab -r を使用するとすべての設定が削除される(タイプミスなどが怖い)ので、2番目のファイルに記載する方法のほうがよさげ。

crontabで設定する

1. helloを1分毎に出力する設定を書く

手始めに動作確認:point_up_tone2:
crontab -e を入力して編集モードにする。vimなどでファイルが開くので、設定を記載する

*/1 * * * * echo "hello" >> /home/vagrant/hello0101.txt

上記を保存して、cronを再起動すると/home/vagrantの配下のhello0101.txtに毎分書き込まれることが確認できる

2. 24時にシャットダウンする設定

ファイル権限は644とかに変更しておく。
/home/vagrant/shutdown.sh

shutdown.sh
#!/bin/bash
sudo shutdown -h now

crontab -e で下記を書き込む

00 * * * * /home/vagrant/shutdown.sh

cron を再起動する

/etc/cron.d/ 配下に設定ファイルを置いて実行する

1. 24時にシャットダウンする設定

ファイル権限は644とかに変更しておく。

実行ファイル
/home/vagrant/shutdown.sh

shutdown.sh
#!/bin/bash
sudo shutdown -h now

/etc/cron.d配下にcronの設定ファイルを配置する

名前は適当にいいっぽいので今回はshutdown
/etc/cron.d/shutdown ファイルをつくって下記を書き込む

SHELL=/bin/bash
MAILTO=""
00 * * * * root /home/vagrant/shutdown.sh

cronを再起動する

ログの確認

cat /var/log/cron

cron再起動

service crond restart

or

/etc/rc.d/init.d/crond restart 

or

/etc/init.d/cron restart

(debian?)

設定書式

crontabで設定

 分 時 日 月 曜日 コマンド

ファイルで設定

 分 時 日 月 曜日 ユーザー コマンド
19
24
1

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
19
24