Setting a Script as a Service on Linux

Sometimes you want to get a script to run automatically on boot of a server, this means setting up a service to call the script.

In this case it was to start a multicast video stream from a raspberry pi, but edit to suit your needs.

Step 1: Create a Service

Copy/paste the following into the file /etc/systemd/system/startup-stream.service:

[Unit]
Description=Multicast Stream Service
[Service]
User=ubuntu
# The configuration file application.properties should be here:
#change this to your workspace
WorkingDirectory=/home/ubuntu/
#path to executable. 
#executable is a bash script which calls jar file
ExecStart=/home/ubuntu/workspace/startup_stream.sh
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target

Step 2: Create a Bash Script to Call Your Service

Here’s the bash script that calls ffmpeg to do it’s thing: startup_stream.sh

#!/bin/bash
ffmpeg -threads 2 -re -fflags +genpts -stream_loop -1 -i thunderbirds.mp4 -c copy -f MPEG-TS udp://239.0.0.1:1234?pkt_size=1316

Don’t forget to give your script execute permission: sudo chmod u+x startup_stream.sh

Step 3: Start the Service

sudo systemctl daemon-reload

sudo systemctl enable startup-stream.service

sudo systemctl start startup-stream.service

sudo systemctl status startup-stream.service

Step 4: Set Up Logging

First, run: 

sudo journalctl --unit=startup-stream.service

See real-time logs by using the -f option.

If you want to trim them, use -n <# of lines> to view the specified number of lines of the log:

sudo journalctl -f -n 1000 -u startup-stream.service

Tail the live log using the -f option:

sudo journalctl -f -u startup-stream.service

Stop the service by using:

sudo systemctl stop startup-stream.service


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *