As Pavel Selivanov points out in this article it is necessary to set DBUS_SESSION_BUS_ADDRESS
and DISPLAY
to enable gui related tasks from a cronjob.
He has written a shell script, which gets the DBUS_SESSION_BUS_ADDRESS
for XFCE, Gnome, Unity, Cinnamon and KDE. I can confirm that is works under ubuntu:16.04
.
$ sudo nano /usr/local/bin/gui-cron
#!/bin/sh
[ "$#" -lt 1 ] && echo "Usage: $0 program options" && exit 1
program="$1"
shift
user=$(whoami)
env_reference_process=$( pgrep -u "$user" xfce4-session || pgrep -u "$user" cinnamon-session || pgrep -u "$user" gnome-session || pgrep -u "$user" gnome-shell || pgrep -u "$user" kdeinit )
export DBUS_SESSION_BUS_ADDRESS=$(cat /proc/"$env_reference_process"/environ | grep -z ^DBUS_SESSION_BUS_ADDRESS= | sed 's/DBUS_SESSION_BUS_ADDRESS=//')
export DISPLAY=$(cat /proc/"$env_reference_process"/environ | grep -z ^DISPLAY= | sed 's/DISPLAY=//')
"$program" "$@"
Then one can create a user cronjob that runs by a given schedule with the crontab syntax. Here e.g. every 15 minutes between 22:00 and 05:59:
$ crontab -e
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
*/15 22-23,00-05 * * * gui-cron gnome-session-quit --power-off
gnome-session-save
manpage: You can specify the --kill argument to terminate the GNOME session. Why on earth would you want to do this periodically? – rozcietrzewiacz Aug 22 '11 at 22:13/var/mail/mechaflash
if you haven't set up anything special. – Gilles 'SO- stop being evil' Aug 23 '11 at 16:44