How to Create a Custom Systemd Service on Ubuntu

In this guide, we will walk you through the steps to create a custom systemd service on Ubuntu that checks if Google Chrome is running every 5 seconds. This can be particularly useful for monitoring purposes.
Prerequisites
- A system running Ubuntu
- Basic knowledge of the terminal and command-line interface
- Google Chrome installed on your system
Step 1: Create the Monitoring Script
First, we need to create a Bash script that will check if Google Chrome is running.
- Open your terminal.
- Create a new script file named
check_chrome.sh
- Add the following content to the script file.
#!/bin/bash
while true; do
# Get the current time
current_time=$(date +"%Y-%m-%d %H:%M:%S")
# Check if Google Chrome is running using pgrep
if pgrep -x "chrome" > /dev/null
then
echo "[$current_time] Google Chrome is running." >> /home/hp/Pradeep-practice/linux/chrome-status.txt
else
echo "[$current_time] Google Chrome is not running." >> /home/hp/Pradeep-practice/linux/chrome-status.txt
fi
# Wait for 5 seconds before repeating the loop
sleep 5
done
Replace /home/hp/Pradeep-practice/linux/chrome-status.txt with the actual path to your txt, Save the file, and exit the editor (Ctrl + X
, then Y
, then Enter
)
Make the script executable
chmod +x check_chrome.sh
Step 2: Create the Systemd Service Unit File
Next, we will create a systemd service unit file to manage our script.
- Open the terminal and create a new service file:
sudo nano /etc/systemd/system/check_chrome.service - Add the following content to the file
[Unit]
Description=chrome status checker
After=network.target
[Service]
ExecStart=/home/hp/Pradeep-practice/linux/check_chrome.sh
[Install]
WantedBy=multi-user.target
Replace /home/hp/Pradeep-practice/linux/check_chrome.sh with the actual path to your script.
Step 3: Enable and Start the Service
To enable and start your custom systemd service, follow these steps:
- Reload the systemd manager configuration:
sudo systemctl daemon-reload - Enable the service to start on boot
sudo systemctl enable check_chrome.service - Start the service
sudo systemctl start check_chrome.service
Step 4: Verify the Service
Finally, check if the service is running correctly.
Check the status of the service: sudo systemctl status check_chrome.service
You should see an output indicating that the service is active and running.
Conclusion
You have now created a custom systemd service on Ubuntu that continuously monitors if Google Chrome is running every 5 seconds.You can use similar steps to create other custom services for different applications as needed.