Using Cron to restart a systemd user service

cronsystemd

I have created a –user service in systemd such that a non privileged user can manage a service. This works well.
I wanted to restart the service at a fixed given time of day, so i created a cron job in the users crontab.

Strangely this does not work. The user can restart the service if they run:

systemctl --user restart myservice.service

However running this from the crontab does not restart the service. Does anyone know why?

This is running on Ubuntu 16.04.

Best Answer

systemctl --user needs to talk to the D-Bus session, which involves setting at least DBUS_SESSION_BUS_ADDRESS and perhaps XDG_RUNTIME_DIR; typically:

XDG_RUNTIME_DIR=/run/user/$(id -u)
DBUS_SESSION_BUS_ADDRESS=unix:path=${XDG_RUNTIME_DIR}/bus
export DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR
systemctl --user restart myservice.service

You might want to look at systemd timers instead of cron for this.

Related Question