I need to emulate the Upstart "start on stopped" behavior, in which service B is started after service A runs to completion, but in systemd. How do I do that?
I've seen references to the "After="
and "Before="
clauses in the [Unit]
section of the *.service
file, but they appear to cause service B to start after service A has been started. Again, I need to wait until service A has run to completion before starting service B.
I put together a trivial example to play with the behavior. I put my *.service
files in /etc/systemd/system
, enabled the two services and then rebooted. I expected to see first.sh
's "…and we're out" before second.sh
's "sleep for 2 seconds," but I didn't get that result, as you'll see below.
I appreciate your guidance.
====
Here are my service files, the scripts they invoke, and the journalctl output.
Here's "first.service":
[Unit]
Description=First of two services
[Service]
ExecStart=/home/steve/play/systemd/oneAfterTheOther/first.sh
[Install]
WantedBy=multi-user.target
Here's "first.sh":
#!/usr/bin/env bash
nsec=10
echo "sleep for ${nsec} seconds"
sleep ${nsec}
echo "...and we're out"
Here's "second.service":
[Unit]
Description=Second of two services
After=first.service
[Service]
ExecStart=/home/steve/play/systemd/oneAfterTheOther/second.sh
[Install]
WantedBy=multi-user.target
Here's "second.sh":
#!/usr/bin/env bash
nsec=2
echo "sleep for ${nsec} seconds"
sleep ${nsec}
echo "...and we're out"
And here, finally, is the journalctl output:
$ journalctl -u first -u second
-- Logs begin at Tue 2018-09-04 17:50:19 CDT, end at Tue 2018-09-04 17:56:37 CDT
Sep 04 17:50:38 sk-xenial-vm systemd[1]: Started First of two services.
Sep 04 17:50:38 sk-xenial-vm systemd[1]: Started Second of two services.
Sep 04 17:50:40 sk-xenial-vm first.sh[900]: sleep for 10 seconds
Sep 04 17:50:40 sk-xenial-vm second.sh[924]: sleep for 2 seconds
Sep 04 17:50:43 sk-xenial-vm second.sh[924]: ...and we're out
Sep 04 17:50:51 sk-xenial-vm first.sh[900]: ...and we're out
Best Answer
I've come upon an answer to my own question.
I read in the systemd.service man page about the "
Type=
" clause, and I see that when I add "Type=oneshot
" to the[Service]
section of my*.service
files, systemd does what I wanted.I expect I could use other
Type=
settings and get results to my liking, and I also expect that I probably don't actually need to makesecond.service
oneshot to get what I want;first.service
is the one I need to see finish. But I have a path to success now.So, for the record, here are the working *.service files and the journalctl output to prove it.
Onward!
====
First.service:
Second.service:
Journalctl output: