Home > Software engineering >  which systemd TYPE of service to use at machine start i some code has to stay forever
which systemd TYPE of service to use at machine start i some code has to stay forever

Time:05-24

at the system start, using a systemd service, I want to lauch a bash to run forever, executing an action every 5 seconds.

Its code is simple (do_every_5_segons.sh)

    while true
    do
        {read some JSON from internet} >> $myLogFile  2>&1
        sleep 5
    done

So, in my service definition I write (~/.config/systemd/user/r4_start.service )

    pi@R4:
    [Unit]
    Description=R4 start 
    
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    Restart=no
    WorkingDirectory=/home/pi/tools
    ExecStart=/home/pi/tools/r4_start.sh

And in the "r4_start.sh", I do some trace and then launch my bash :

    nohup /home/pi/python/do_every_5_segons.sh &

The "&" is required so more init can be done after this line.

The "nohup" is required so the shell survives parent end.

My question is :

  • what is the correct service "Type" for this situation ?

CodePudding user response:

Do not use nohup. Do not use &. Do not wrap your script in another script. Doing either of these first two things stops systemd from detecting when your program crashed and restarting it, and the third complicates signal handling.

Do use Restart=always. Do create an Install section, and configure your service to be a dependency of a target that is started on boot.

[Unit]
Description=R4 start 

[Service]
WorkingDirectory=/home/pi/tools
ExecStart=/home/pi/tools/run-poll-loop
Restart=always

[Install]
WantedBy=multi-user.target

...where run-poll-loop is executable (chmod x) and contains your logic (note, command names should not have extensions; .sh is bad practice):

#!/usr/bin/env bash
while :; do
  # ...do whatever you need here...
  sleep 5
done

Note that for a slower delay than every-5-seconds, I would suggest a systemd timer running a oneshot service that only does a single iteration of the loop each time; but for this short a timer, that would add up to quite a bit of process-startup overhead.

  • Related