LoginSignup
344
272

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-12-25

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つのディレクトリにすべてまとまり管理しやすいです。

344
272
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
344
272