69

I want systemd to start a script and retry a maximum of 5 times, 30s apart. Reading the systemd.service manual and searching the Internet didn't produce any obvious answers.

jross
  • 1,847
  • 2
  • 10
  • 6
  • 2
    Just in case this is how you could do it with [immortal](https://immortal.run/post/retries/) `immortal -w 30 -r 5 ` – nbari Jan 10 '18 at 14:37
  • 1
    Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask. – jww Aug 21 '18 at 09:27
  • 1
    https://serverfault.com/questions/736624/systemd-service-automatic-restart-after-startlimitinterval/962338 – Channa Dec 30 '20 at 04:25

1 Answers1

103

To allow a maximum of 5 retries separated by 30 seconds use the following options in the relevant systemd service file.

[Unit]
StartLimitInterval=200
StartLimitBurst=5

[Service]
Restart=always
RestartSec=30

This worked for a service that runs a script using Type=idle. Note that StartLimitInterval must be greater than RestartSec * StartLimitBurst otherwise the service will be restarted indefinitely. The service is considered failed when restarted StartLimitBurst times within StartLimitInterval.

See https://www.freedesktop.org/software/systemd/man/systemd.unit.html#StartLimitIntervalSec=interval and https://www.freedesktop.org/software/systemd/man/systemd.service.html#RestartSec=

Victor Häggqvist
  • 4,484
  • 3
  • 27
  • 35
jross
  • 1,847
  • 2
  • 10
  • 6
  • 8
    It's maybe worth noting that -- according to the official systemd manpages -- RestartSec and Restart are part of [System], whereas StartLimitInterval and StartLimitBurst are part of [Unit]. – Johann Hagerer Jun 14 '17 at 12:26
  • 12
    What does StartLimitInterval do? – sid-kap Oct 11 '17 at 19:16
  • 12
    @GerhardHagerer When you say [System], I think you mean [Service]. This worked for me. – Haakon Jan 09 '18 at 10:34
  • 4
    also worked for 'Type= forking' for me, if that means anything. – fei0x Feb 15 '18 at 22:09
  • 4
    also, more details here: https://www.freedesktop.org/software/systemd/man/systemd.unit.html# and here: https://www.freedesktop.org/software/systemd/man/systemd.service.html#Examples – fei0x Feb 15 '18 at 22:11