1

I'm trying to setup automatic execution of a process using a systemd timer and service. The problem is that my oneshot service gets immediately killed on shutdown. How can I tell systemd to not kill oneshot services but wait for it to finish before shutdown?

My test.service looks like this:

[Unit]
Description=My automatic updates
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/bin/sleep 40
TimeoutSec=0
11
  • Can't you use just Type=simple?
    – paladin
    Commented Feb 20 at 10:43
  • @paladin Can you explain how this change alters how systemd handles the running unit at shutdown? (I'm here with the exact same question as OP.)
    – Headbank
    Commented Feb 22 at 15:08
  • freedesktop.org/software/systemd/man/latest/… search for "oneshot", in short, if you use default settings, systemd will regard a oneshot service as dead after it had been started. Meaning, if you shutdown your system, a wrongly configured oneshot service (which actually is not dead, but regarded as dead by systemd) will look like a malfunctioning service for systemd and thus being killed. You could also use RemainAfterExit= option to counteract this.
    – paladin
    Commented Feb 22 at 16:10
  • 1
    PS also take a look at ExecStop=
    – paladin
    Commented Feb 22 at 16:18
  • 1
    @Headbank yes, this was what I was looking for and I came to the same result like you. But I can live with the workaround described in the question: ignoring the TERM signal in my script. Thanks for your suggestions.
    – Schorschii
    Commented Mar 1 at 18:39

1 Answer 1

2

So I found 2 possible solutions.

  1. Tell your script to ignore the TERM signal and set TimeoutStopSec=infinity to avoid systemd SIGKILL your process after it is not responding to SIGTERM. Ignoring the TERM signal can be done e.g. by using trap in bash or something in Python like:

    import signal
    def signal_handler(signum, frame):
      pass
    signal.signal(signal.SIGTERM, signal_handler)
    

    You should implement a logic to exit your script as soon as possible when receiving the TERM signal.

  2. If you can't modify the executable, set KillSignal= to something non-destructive like SIGCONT (I consider this as a hack and not recommend this).

1
  • 1
    On a general pragmatic note I would advise using a suitably high value for TimeoutStopSec (as much head-room to allow for worst-case) instead of infinity because making it potentially impossible to ever shutdown seems unadvisable (or do you trust your service enough to be sure this will never arise?).
    – Headbank
    Commented Mar 6 at 10:19

You must log in to answer this question.

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