crontabを捨てsystemdに定期実行を任せよう。

Linux環境で定期的に実行させたい処理はcronで処理するのが一般的かと思います。

30分毎に exec.sh を実行する。

$ crontab -e

0,30 * * * *   /bin/sh ~/exec.sh

systemd

systemdはサービスを管理するための仕組みですが、
例えば、nginxをずっと起動していたいときに

$ systemctl start nginx.service

みたいな使いかたで、システムをデーモン化するために用いるのがよくある使用方法でしょうか。

$ systemctl enable nginx.service

また、enable で自動起動させるような使い方もあります。

systemdを作ってみる

〇〇.service という設定ファイルを所定の場所に配置するだけで、使用できるようになります。

/etc/systemd/system/exec.service
[Unit]
Description=run exec.sh

[Service]
Type=simple
ExecStart=/bin/sh ~/exec.sh

[Install]
WantedBy=multi-user.target

ExecStart= の部分に実行したいコマンドを入力するだけです。

起動してみる

これでsystemdの起動コマンドで、さきほど作成したserviceファイルが実行されるようになります。

$ systemctl start exec.service

status で実行結果がみられます。

$ systemctl status exec.service
● exec.service - run exec script

定期実行させる

ここで本題の定期実行です。
systemdにはtimerという機能もあります。

先程作成した 〇〇.service と一緒のディレクトリに 〇〇.timer という設定ファイルを加えます。
〇〇に入るファイル名は共通です。

/etc/systemd/system/exec.timer
[Unit]
Description=timer exec.sh

[Timer]
OnUnitActiveSec=30m

[Install]
WantedBy=timers.target

これだけで冒頭のcronと同様の処理が可能です。
OnUnitActiveSec=30m という書き方ができ、30分毎に実行されるのが直感的です。

$ systemctl start exec.timer

起動から30毎に実行される。

$ systemctl enable exec.timer

ログはsystemdなのでjournalctlで確認可能です。

$ journalctl -f -u exec.service

systemd.timerのメリット

systemdで設定するメリットとして設定を細かくできる点にあります。

Persistent=true で起動時に時間を待たずにすぐに実行開始したり、
OnBootSec=20min で逆に起動後20分後から実行するように調整したり可能です。

cronを使用するうえでよく問題になりがちなユーザーと権限の問題も.service側に
User=username で好きなuserに実行させることができ、設定ファイルも1つのディレクトリにすべてまとまり管理しやすいです。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account