Linux - 只要用户登录,每 5 分钟运行一次脚本

Linux - 只要用户登录,每 5 分钟运行一次脚本

我需要在用户登录时运行一个脚本,并且只要用户登录,就需要每 5 分钟运行一次该脚本。脚本应在用户安全上下文中运行,并在用户注销时停止运行。我为不同的用户手动添加了 crontab 行:

*/5 * * * * whoami >> /tmp/<username>.txt

该脚本确实在每个用户上下文中开始运行,但它从未停止运行。即使在用户注销后,脚本仍继续向tmp文件夹中的文本文件添加行。

有没有办法在登录用户环境中每 5 分钟运行一次脚本,直到注销?

答案1

我建议一个systemd解决方案:您需要一个服务文件,例如 my5min_script.service

[Unit]
#just what it does
Description= run script every 5 min as long as user is logged in

[Service]
#we assume the full service as active one the script was started
Type=simple
#where to find the executable
ExecStart=/path/to/script
#what you want: make sure it always is running every 5 minutes
Restart=always
RestartSec=5min

[Install]
#which service wants this to run - default.target is just it is loaded by default
WantedBy=default.target

现在将此文件放入/etc/systemd/user/并通过激活

systemctl --user --global enable my5min_script

就像脚本 a) 以用户身份运行 b) 由每个用户(全局)运行,并且开始和结束与用户特定绑定default.target,通过登录/注销激活和停止。

更多详细信息请参见建筑维基

相关内容