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" -x xfce4-session || pgrep -u "$user" -x cinnamon-session || pgrep -u "$user" -o gnome-session || pgrep -u "$user" -x gnome-shell || pgrep -u "$user" -x 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-savemanpage: You can specify the --kill argument to terminate the GNOME session. Why on earth would you want to do this periodically?