1

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.

  • Please paste output of command crontab -l. You have to execute it as user which have permissions to this service. The other question is: why do you want to restart it using cron? – mrc02_kr Oct 10 '18 at 8:34
3

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.

  • This worked. Thanks. Is there a reason why cron should not be used in this case? – Magnus Jørgensen Oct 10 '18 at 8:58
  • 1
    No particular reason, I only suggested timers because they should deal with all this transparently (but I haven’t used timers for user services so I don’t know how to do it and whether it would work). – Stephen Kitt Oct 10 '18 at 9:00
  • 1
    There is a reason with respect to the larger point made in a question comment. Often in my experience this sort of scheduled externally forced restart is a bodge, that papers over an underlying problem. – JdeBP Oct 10 '18 at 11:11
  • 1
    systemd user services only run while there is a user session, whereas the cronjob would probably still run if there’s no user session. (That’s why the cronjob doesn’t know about the dbus session: cron exists outside of the session.) I agree that a systemd timer is the better solution here. – Lucas Werkmeister Oct 11 '18 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.