What is the best way to delay system shutdown by arbitrary amount of time in systemd?

I'm trying the following unit:

root@ip-172-30-3-65:~# cat /etc/systemd/system/delay_by30.service
Description=Delay Shutdown by 30 sec.
#Before=apache2 nginx php5-fpm

ExecStop=/bin/sleep 30


However I'm getting very mixed up results. For the starters my ExecStop line somehow is executed on systemctl start and my ExecStart on systemctl stop, other way around than it should be. Time stamps in the journalctl confirm this:

root@ip-172-30-3-65:~# systemctl enable delay_by30.service 
Created symlink from /etc/systemd/system/multi-user.target.wants/delay_by30.service to /etc/systemd/system/delay_by30.service.
root@ip-172-30-3-65:~# systemctl start delay_by30.service 
root@ip-172-30-3-65:~# systemctl stop delay_by30.service 
root@ip-172-30-3-65:~# journalctl -n 4 -u delay_by30
-- Logs begin at Fri 2017-01-06 17:05:34 GMT, end at Mon 2017-01-09 15:57:34 GMT. --
Jan 09 15:55:59 ip-172-30-3-65 systemd[1]: Starting Delay Shutdown by 30 sec....
Jan 09 15:56:29 ip-172-30-3-65 systemd[1]: Started Delay Shutdown by 30 sec..
Jan 09 15:57:34 ip-172-30-3-65 systemd[1]: Stopped Delay Shutdown by 30 sec..
  • 1
    What are you trying to accomplish ? – don_crissti Jan 9 '17 at 16:13
  • When systemd is instructed to should down the system, it should sleep at least 30 secs before doing so. – NarūnasK Jan 9 '17 at 16:15
  • 1
    @NarūnasK That's what you're trying to do, but what are you trying to accomplish by doing that? There's probably something even better which can solve your actual root problem. – mattdm Jan 9 '17 at 16:17
  • @don_crissti Totally irrelevant, but if you must know: host shuts down quicker than AWS LB can notice it, hence delayed shutdown solves this problem, otherwise LB send traffic to host, which does not exists. – NarūnasK Jan 9 '17 at 16:22

You need to add RemainAfterExit=yes to your [Service] section. Right now systemd is seeing your process (/bin/echo) exit, at which point it considers the service to have exited, and proceeds to stop it.

(You can probably also just not have an ExecStart line, but I didn't test that.)

  • indeed the ExecStart isn't needed, as explained here... – don_crissti Jan 9 '17 at 16:35
  • Without ExecStart it would be ideal, however I'm getting delay_by30.service lacks ExecStart setting. Refusing. – NarūnasK Jan 9 '17 at 16:36
  • @NarūnasK I'd guess it depends on the systemd version. – derobert Jan 9 '17 at 17:18

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.