将通知发送与 cron 结合使用

将通知发送与 cron 结合使用

我正在使用 Arch Linux 和 KDE/Awesome WM。我正在努力 notify-send与 一起工作cron

我尝试过设置DISPLAY/XAUTHORITY变量,并notify-send使用“sudo -u”运行,但都没有结果。

我可以从会话中交互地调用通知发送并获取通知。

FWIW,cron 作业运行良好,我通过将内容回显到临时文件来验证。只是“通知发送”不起作用。

代码:

[matrix@morpheus ~]$ crontab -l
* * * * *  /home/matrix/scripts/notify.sh

[matrix@morpheus ~]$ cat /home/matrix/scripts/notify.sh
#!/bin/bash
export DISPLAY=127.0.0.1:0.0
export XAUTHORITY=/home/matrix/.Xauthority
echo "testing cron" >/tmp/crontest
sudo -u matrix /usr/bin/notify-send "hello"
echo "now tested notify-send" >>/tmp/crontest

[matrix@morpheus ~]$ cat /tmp/crontest
testing cron
now tested notify-send

[matrix@morpheus ~]$ 

正如您所看到的,通知发送工作之前和之后的回显。
我也尝试过设置DISPLAY=:0.0

更新:我又搜索了一些发现DBUS_SESSION_BUS_ADDRESS需要设置。在使用我从交互式会话中获得的值对其进行硬编码后,屏幕上每分钟都会弹出一个小小的“hello”消息!

但问题是这个变量并不是永久的,所以我将尝试那里建议的命名管道解决方案。

[matrix@morpheus ~]$ cat scripts/notify.sh
#!/bin/bash
export DISPLAY=127.0.0.1:0.0
export XAUTHORITY=/home/matrix/.Xauthority
export DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-BouFPQKgqg,guid=64b483d7678f2196e780849752e67d3c
echo "testing cron" >/tmp/crontest
/usr/bin/notify-send "hello"
echo "now tested notify-send" >>/tmp/crontest

由于cron似乎不支持通知发送(至少不直接支持),是否有其他更cron友好的通知系统可供我使用?

答案1

您需要设置该DBUS_SESSION_BUS_ADDRESS变量。默认情况下 cron 无权访问该变量。为了解决这个问题,请将以下脚本放在某处并在用户登录时调用它,例如使用惊人的以及run_oncewiki上提到的功能。任何方法都可以,因为如果调用该函数的次数超过所需的次数,也不会造成损害。

#!/bin/sh

touch $HOME/.dbus/Xdbus
chmod 600 $HOME/.dbus/Xdbus
env | grep DBUS_SESSION_BUS_ADDRESS > $HOME/.dbus/Xdbus
echo 'export DBUS_SESSION_BUS_ADDRESS' >> $HOME/.dbus/Xdbus

exit 0

这将创建一个包含所需 Dbus 环境变量的文件。然后在 cron 调用的脚本中,通过获取脚本来导入变量:

if [ -r "$HOME/.dbus/Xdbus" ]; then
  . "$HOME/.dbus/Xdbus"
fi

这是使用相同机制的答案。

答案2

您需要在 crontab 本身中设置变量:

DISPLAY=:0.0
XAUTHORITY=/home/matrix/.Xauthority

# m h  dom mon dow   command 
* * * * *  /usr/bin/notify-send "hello"

不需要sudo,至少在我的系统上不需要。

答案3

我在 Ubuntu 18.04 上使用 i3。我解决这个问题的方法是:

* * * * * XDG_RUNTIME_DIR=/run/user/$(id -u) notify-send Hey "this is dog!"

答案4

这句俏皮话对我在 Manjaro 和 Cronie 中有用:

# Note: "1000" would be your user id, the output of... "id -u <username>" 
10 * * * * pj DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus notify-send 'Hello world!' 'This is an example notification.'

没有非常丑陋的 DBUS_blah_blah 它根本不起作用。我也发现journalctl -xb -u cronie很有帮助。 FWIW,Cronie 使用 crond 并且应该向后兼容 Vixie cron。

我在这里找到了解决方案https://wiki.archlinux.org/index.php/Desktop_notifications

更新:2021 年仍然有效。我将这些提示添加到我的 /etc/crontab 文件中。

# After installing cronie:
# systemctl start cronie
# systemctl enable cronie

# After editing this file:
# chmod 600 /etc/crontab    
# crontab /etc/crontab
# Check that the changes are set:
# crontab -l

相关内容