Cron与notify-send

Rav*_*avi 16 linux cron notify

我需要显示来自cron作业的通知.我的crontab是这样的:

$ crontab -l
# m h  dom mon dow   command
  * *   *   *   *    Display=:0.0 /usr/bin/notify-send Hey "How are you"
Run Code Online (Sandbox Code Playgroud)

我检查过/var/log/syslog,命令实际上每分钟执行一次,但它没有弹出通知.谁能帮助我理解为什么?

Mr.*_*ito 55

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

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

2020 年编辑:我仍然在 Ubuntu 20.04 上使用它。

  • 可以确认这在 Ubuntu 18.04 上有效,而接受的答案却无效。 (8认同)
  • 当确认的答案不起作用时,可以确认这在 Ubuntu 20.04 上有效。 (6认同)
  • 当确认的答案不起作用时,可以确认这在 Ubuntu 22.04 上有效。 (3认同)
  • 这在 ubuntu 22.04 上对我有用 (3认同)
  • 现在这应该是确定的答案了。我下意识地直接转到已接受的答案,但它不起作用,因此最初错过了工作解决方案。 (2认同)

Rav*_*avi 17

我找到了答案:

$ crontab -l
# m h  dom mon dow   command
  * *   *   *   *    export DISPLAY=:0.0 && export XAUTHORITY=/home/ravi/.Xauthority && sudo -u ravi /usr/bin/notify-send Hey "How are you"
Run Code Online (Sandbox Code Playgroud)

谢谢,拉维

  • 只需添加"export DISPLAY =:0.0"就可以解决这个问题.也就是说,cronjob在我的用户帐户下运行.从与弹出窗口需要出现的帐户不同的帐户运行时,可能需要XAUTHORITY.谢谢. (4认同)
  • 我也是.我可以将此命令缩减为`*****export DISPLAY =:0.0 && notify-send Hey"你好吗?" (3认同)
  • 它可以进一步简化为`* * * * * DISPLAY=:0.0 notify-send Hey "How are you"` (2认同)

nma*_*max 7

在 Ubuntu 14.04 中,导出显示对我不起作用。下面是当笔记本电脑的电池状态变得太低时我用来关闭虚拟机的 cron 脚本。行设置 DBUS_SESSION_BUS_ADDRESS 是最终使警告正常工作的修改。

#!/bin/bash

# if virtual machine is running, monitor power consumption
if pgrep -x vmware-vmx; then

  bat_path="/sys/class/power_supply/BAT0/"

  if [ -e "$bat_path" ]; then

    bat_status=$(cat $bat_path/status)

    if [ "$bat_status" == "Discharging" ]; then

      bat_current=$(cat $bat_path/capacity)

      # halt vm if critical; notify if low
      if [ "$bat_current" -lt 10 ]; then

        /path/to/vm/shutdown/script
        echo "$( date +%Y.%m.%d_%T )" >> "/home/user/Desktop/VM Halt Low Battery"

        elif [ "$bat_current" -lt 15 ]; then
        eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
        notify-send -i "/usr/share/icons/ubuntu-mono-light/status/24/battery-caution.svg"  "Virtual machine will halt when battery falls below 10% charge."

      fi

    fi

  fi

fi

exit 0
Run Code Online (Sandbox Code Playgroud)

相关线路在这里:

eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
Run Code Online (Sandbox Code Playgroud)

我在这里找到了解决方案:https : //askubuntu.com/a/346580/255814


fan*_*ing 6

只有这对我有用(Xubuntu)

eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME xfce4-session)/environ)"; notify-send  "hello world" 
Run Code Online (Sandbox Code Playgroud)

如果您在 gnome 环境中,则需要更改xfce4-sessiongnome-session

参考:https : //askubuntu.com/questions/298608/notify-send-doesnt-work-from-crontab


小智 6

添加DBUS_SESSION_BUS_ADDRESS\xef\xbc\x9a

\n\n

* * * * * DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus /usr/bin/notify-send 'helloworld..' 'msg...'

\n