如何根据文件的修改日期运行 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.


相关内容