9

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.

1
  • 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, 2018 at 8:34

2 Answers 2

15

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.

5
  • This worked. Thanks. Is there a reason why cron should not be used in this case? Oct 10, 2018 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). Oct 10, 2018 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, 2018 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. Oct 11, 2018 at 12:50
  • Starting/stopping a service with a timer does not work though, since as soon as the timer triggers all you get is an infinite restart loop of said service. Jul 2, 2022 at 7:09
-1

Same issue.

Adding ; 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

In Lubuntu 22.04 fixed the issue

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Feb 13 at 18:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .