ファイルの変更日に基づいてcrontabを実行するには?

ファイルの変更日に基づいてcrontabを実行するには?

file.configの変更日が最近の場合にfile.pyを実行する方法はありますか?ファイルが変更されたら、スクリプトを実行するのと同じですか?

よろしくお願いします!

ベストアンサー1

これはsystemdを介して行うことができます。パス単位:

# /etc/systemd/system/file.path
[Unit]
Description=Watches file.config for changes

[Path]
PathChanged=/path/to/file.config

[Install]
WantedBy=multi-user.target

ファイルが変更されるたびに監視されfile.configトリガーされます。以下を使用してPythonスクリプトを実行できます。file.servicefile.service

#/etc/systemd/system/file.service
[Unit]
Description=Does something after changing file.config

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /path/to/file.py

それをテストするために使用しますsystemctl start file.path。次にtouch /path/to/file.config。火を見なければなりませんfile.py

カタログもご覧いただけます。新しいファイルがディレクトリに追加されたら、パスをトリガーしてそのファイルを処理できます。


私のシステムでいくつかのテストを実行して動作していることを確認しました。

stew@laptop:~/.config/systemd/user$ cat file.{path,service}
[Path]
PathChanged=%h/file
[Service]
Type=oneshot
ExecStart=/bin/bash -c 'echo I did something'

$ systemctl --user start file.path
$ touch ~/file
$ systemctl --user status file.service
● file.service
     Loaded: loaded (/home/stew/.config/systemd/user/file.service; static)
     Active: inactive (dead) since Fri 2022-08-05 16:29:44 CEST; 1s ago
TriggeredBy: ● file.path
    Process: 296588 ExecStart=/bin/bash -c echo I did something (code=exited, status=0/SUCCESS)
   Main PID: 296588 (code=exited, status=0/SUCCESS)
        CPU: 2ms

Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:29:44 SIM-5532-007 bash[296588]: I did something
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Finished file.service.
$ touch ~/file
$ touch ~/file
$ journalctl --user -u file.service -f
-- Journal begins at Mon 2022-05-30 10:11:55 CEST. --
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:29:44 SIM-5532-007 bash[296588]: I did something
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:29:44 SIM-5532-007 systemd[1746]: Finished file.service.
Aug 05 16:29:50 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:29:50 SIM-5532-007 bash[296594]: I did something
Aug 05 16:29:50 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:29:50 SIM-5532-007 systemd[1746]: Finished file.service.
Aug 05 16:30:10 SIM-5532-007 systemd[1746]: Starting file.service...
Aug 05 16:30:10 SIM-5532-007 bash[296621]: I did something
Aug 05 16:30:10 SIM-5532-007 systemd[1746]: file.service: Succeeded.
Aug 05 16:30:10 SIM-5532-007 systemd[1746]: Finished file.service.


おすすめ記事