23

I have a question regarding making my own unit (service) file for Systemd.

I've read the documentation and had some questions. After searching around, I found this very helpful answer that gives some detail about some of the questions I was having.

How to write a systemd .service file running systemd-tmpfiles

Although I find that answer useful, there is still one part that I do not understand. Mainly this part:

Since we actually want this service to run later rather than sooner, we then specify an "After" clause. This does not actually need to be the same as the WantedBy target (it usually isn't)

My understanding of After is that it is pretty straight forward. The service (or whatever you are defining) will run after the unit listed in After.

Similarly, WantedBy seems pretty straight forward. You are defining that the unit you list has a Want to your service. So for a target like multi-user or graphical, your unit should be run in order for systemd to consider that target reached.

Now, assuming my understanding of how these declarations work is correct so far, my question is this: Why would it even work to list the same unit in the After and WantedBy clauses?

For example, defining a unit that is After multi-user.target and also WantedBy multi-user.target seems to me like it would lead to an impossible situation where the unit needs to be started after the target is reached, but also it needs to be started for the target to be considered "reached".

Am I misunderstanding something?

2
  • 2
    I have the same question. May 10, 2019 at 0:04
  • 2
    I learned what WantedBy does by reading your question! :D Have my upvote.
    – aderchox
    Nov 27, 2021 at 13:27

2 Answers 2

10

The systemd manual discusses the relationship between Before/After and Requires/Wants/Bindto in the Before=, After= section:

Note that this setting is independent of and orthogonal to the requirement dependencies as configured by Requires=, Wants= or BindsTo=. It is a common pattern to include a unit name in both the After= and Requires= options,

After does not imply Wants or WantedBy, nor does it conflict with those settings.

If both units are triggered to start, After will affect the order, regardless of the dependency chain.

If the module listed in After is not somewhere in the dependency chain, it won't be loaded, since After does not imply any dependency.

3

WantedBy does not influence the order in which services are started. As stated in systemd unit manual, in the WantedBy and RequiredBy description:

This has the effect that a dependency of type Wants= or Requires= is added from the listed unit to the current unit.

Then in the Wants description it states that it is a weaker version of Requires where it states:

Note that requirement dependencies do not influence the order in which services are started or stopped.

You must log in to answer this question.

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