1

I'm creating something to allow me to set limits for time spent per user session: I've created a cron job:

*/120 * * * 1,2,3,4,5 /path/to/command
*/180 * * * 0,6 /path/to/command

and I want to run logout (and possibly shutdown as there's a BIOS password set), could someone tell me how to run both of those via cron?.

Hans
  • 1,281
  • 1
  • 20
  • 44
Kieran
  • 41

2 Answers2

3
*/150 * * * 0,6 gnome-session-quit

Works fine.

Kieran
  • 41
1

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
derHugo
  • 3,356
  • 5
  • 31
  • 51
swiesend
  • 111