Using notify-send with cron

Viewed 2581

I've been trying to use notify-send with cron. I've checked out tons of answers given on stackoverflow and other forums. But I don't see the notify-send popup appearing. I'm currently running Ubuntu 13.10. I've been able to get this to work earlier (about 3 months ago when I had Ubuntu 11.10) but I don't remember how and I don't see what I'm doing wrong here.

My current crontab looks like:

*/1 * * * * export DISPLAY=:0.0 && export XAUTHORITY=/home/harold/.Xauthority && /usr/bin/notify-send "$(date)"

I've tried many solutions given online including using sudo -u harold right before /usr/bin/notify-send .... I've also tried using export DISPLAY=:0 instead of =:0.0. The popup still doesn't appear.

I've also tried to create a script. The cron job to run the script looks like:

*/1 * * * * cd /home/harold/bin && ./notify-send-test.sh

And my script (notify-send-test.sh) looks like:

#!/bin/bash
#export DISPLAY=:0
#export XAUTHORITY=/home/harold/.Xauthority
/usr/bin/notify-send "$(date)"
echo "trying to notify at $(date)" >> /home/harold/bin/cronlog.txt

I've tried using the commented lines and not using them. None of the combinations seem to work. I've also tried using export DISPLAY=0.0.

I do get the expected output in the cronlog.txt file every minute. This means that my script is being executed but the notify-send is not.

I would like to know what I am doing wrong. Happy to provide any more information that may be of use.

Secondary question: There was also something about cron not being able to use certain environment variables. I don't get what that meant and how it affects the way I use cron. It would be nice if someone could explain this.

2 Answers

To add to Sakthi's answer.

You can get the DBUS_SESSIONBUS_ADDRESS withouth using nautilus (or gnome or whatever) by typing dbus-launch (see this answer)

So to the script would simply be:

#!/bin/bash
export $(dbus-launch)
/usr/bin/notify-send "$(date)"

If that doesn't work, you could try setting it hard-coded to your user ID:

#!/bin/bash
userid=$(id -u)
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$userid/bus"
export DBUS_SESSION_BUS_ADDRESS
/usr/bin/notify-send "$(date)"

You can add echo $(env | grep DBUS_SESSION_BUS_ADDRESS) in the script to check what the env variable is when the script is executed.

Related