Cron with notify-send

前端 未结 13 1216
我寻月下人不归
我寻月下人不归 2020-12-09 10:06

I need to show a notification from a cron job. My crontab is something like:

$ crontab -l
# m h  dom mon dow   command
  * *   *   *   *    Display=:0.0 /usr         


        
相关标签:
13条回答
  • 2020-12-09 10:10

    In Ubuntu 14.04 exporting the display did not work for me. Below is a cron script I'm using to shutdown a virtual machine when a laptop's battery state becomes too low. The line setting DBUS_SESSION_BUS_ADDRESS is the modification that finally got the warnings working correctly.

    #!/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
    

    The relevant line is here:

    eval "export $(egrep -z DBUS_SESSION_BUS_ADDRESS /proc/$(pgrep -u $LOGNAME gnome-session)/environ)";
    

    I found the solution here: https://askubuntu.com/a/346580/255814

    0 讨论(0)
  • 2020-12-09 10:10

    May be you can try:

    * * * * * env DISPLAY=:0.0 sudo -u ravi /usr/bin/notify-send Hey "How are you"

    0 讨论(0)
  • 2020-12-09 10:12

    I created a /usr/bin script that uses the DISPLAY-:0.0 technique http://pastebin.com/h11p2HtN

    It doesn't take XAUTHORITY into account. I'll have to investigate that further.

    0 讨论(0)
  • 2020-12-09 10:16

    I found the answer:

    $ 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"
    
    0 讨论(0)
  • 2020-12-09 10:22

    I use i3 on Ubuntu 18.04. My way to solve this is:

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

    Edit 2020: I still use it on Ubuntu 20.04.

    0 讨论(0)
  • 2020-12-09 10:23

    add DBUS_SESSION_BUS_ADDRESS

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

    0 讨论(0)
提交回复
热议问题