Using systemd --user to run fetchmail

Fetchmail usually runs either as a single system wide daemon, or it's started by a user's cron job. But as you can see, the above fetchmail uses IMAP4's IDLE feature. So it has to keep a connection to the server open. Fetchmail can do this for only one connection at a time.

To me, that is enough, but I want my personal fetchmail instance to always run, not merely when I'm logged in. Luckily, systemd has a user feature that does exactly that.

Procedure 1.  Running Fetchmail from Systemd
  1. We want that fetchmail to start at boot, not merely when I log in. Systemd calls it lingering (see also here), and we have to enable it as root (merely once) for the user:

    sudo loginctl enable-linger apprentice

  2. Systemctl talks to DBus. When calling systemctl through sudo for another user, there may be a bit of a problem because XDG_RUNTIME_DIR is not set properly. We can easily solve this in ~/.bashrc:

    export XDG_RUNTIME_DIR="/run/user/$(id -u)"

    Now when root sudos -s to become apprentice, it won't get

    Failed to connect to bus: No such file or directory

  3. Shown here is how to do it from the root account. But the user can also do it himself. XDG_RUNTIME_DIR here still has to be set from the command line because sudo doesn't use Bash:

    sudo -u apprentice XDG_RUNTIME_DIR=/run/user/$(id -g apprentice) systemctl --user enable fetchmail


    This command creates a further structure under ~/.config/systemd/user. If the WantedBy line in the unit file changes, that structure would chage as well, and this command has to be re-run. A daemon-reload is not enough.

  4. apprentice@host:~$ systemctl --user start fetchmail

After this, fetchmail will run for the user as soon as the system is booted.