How to call zenity from cron script?
Found answer here. Add to ~/.bashrc
:
xhost local:$USER > /dev/null
and then use zenity in script evoked by cron like this:
zenity --error --text='Something very bad has happened!' --display=:0.0
adding --display=:0.0
is what's important
To run a GUI command on cron, you'll have to tell cron what display the program should use. For that you use:export DISPLAY=:0
For a zenity notification each 30 minutes, edit with crontab -e
and set a job like:
*/30 * * * * export DISPLAY=:0 && /somedirectory/your_zenity_script.sh
Detailed how to: link
There's another possible solution if you want it to work regardless of
username, by finding the active user of the X display, using
ConsoleKit (the command ck-list-sessions
). Assuming the below script
is run as root, it will show a zenity message to the current active
user on your computer:
#!/bin/bash
ACTIVE=$(ck-list-sessions | awk -F' = ' '
function f(){if(A=="TRUE"){P=U"\t"D;gsub("'"'"'","",P);print P}}
$1=="\tunix-user"{U=$2}
$1=="\tx11-display"{D=$2}
$1=="\tactive"{A=$2}
END{f()} /^[^\t]/{f()}
')
USERID=${ACTIVE% *} # tab
USERNAME=$(getent passwd $USERID|cut -f1 -d':')
DISPLAY=${ACTIVE#* } # tab
DISPLAY="$DISPLAY" su $USERNAME -c "zenity --error --text='Something very bad has happened!'"
The little awk script is just for parsing ck-list-sessions and outputting the username and display of the user that is active (could also require that it's a local connection if you want to exclude ssh -X users, if you want).
(I use this in a backup script that runs on plugging in a USB drive.)