24

I have a really strange issue with systemd. When I issue a systemctl restart it will start the new process before the previous one finishes.

This can be seen in the log, where the final shutdown message ("closing log") is logged after the startup message ("opening log").

Is there any way to add a delay between the stop and the start of process?

2
  • Nothing stopping you from running systemctl stop myservice && sleep 3 && systemctl start myservice Commented Jul 11, 2016 at 11:17
  • 1
    Why is that strange? It's a design feature to leave you alone to work around real world issues. Inject the sleep in your Unit start or use an ExecPre condition to ensure the old instance is fully gone. Commented Dec 9, 2016 at 15:53

3 Answers 3

30

In your systemd service files, you can set RestartSec option to add a delay for restart. See example below:

[Service]
Restart=always
RestartSec=30

Check this link for more examples.

2
  • 5
    afaik RestartSec only applies to services configured with the Restart= directive and is not taken into account when doing a systemctl restart someservice Commented Jul 11, 2016 at 11:17
  • Link is dead, maybe look at systemd.service, RestartSec= Commented Mar 10 at 14:52
4

RestartSec seems to only be used if that particular service is the one being restarted via the systemctl restart command.

For example, I have two services, A and B.

[Unit]
Requires=network-online.target
[Service]
ExecStart=A-stuff
Restart=always

and

[Unit]
Requires=A.service
After=A.service
[Service]
ExecStart=B-stuff
Restart=always
RestartSec=30

If you do a systemctl restart B, it works as expected... but if you do a systemctl restart A, both services are stopped and immediately started again, with no delay.

Systemd is apparently only using the configuration values for the one service you specify, and ignoring them for any dependencies.

This is not as uncommon as it sounds. If B talks to a remote server, starting and stopping quickly may fail due to the remote end rejecting the client. But restarting A directly will happen whenever A is updated without a change to B.

You can probably work around this by adding the delay to A as well, but you shouldn't NEED to do this, as it breaks object isolation by making A know about B when it's not a dependency.

1

You may use ExecStopPost, which allows to run a command after the service stopping:

ExecStopPost=/bin/sleep 5

Then the service will wait for 5 seconds after each stopping (including manual restart or the service killing). It will not be possible to start it sooner then 5 seconds after its stopping.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.