Systemd is a software application that provides an array of system components for Linux operating systems. It is the first service to initialize the boot sequence. This always runs with pid 1. This also helps use to manage system and application service on our Linux operating system.
We can also run any custom script as systemd service. It helps the script to start on system boot. This can be helpful for you to run any script which required to run at boot time only or to run always.
This tutorial coverts to run a shell script as Systemd service.
- Create a shell script
#!/bin/bash
DATE=`date '+%Y%m%d-%H%M%S'`
LogNameDATE=`date '+%Y%m%d'`
/home/kafka/kafka/bin/connect-standalone.sh /home/kafka/kafka/config/connect-standalone.properties /home/kafka/kafka/config/connect-debezium-postgresql.properties >>/root/PgsqlKafkaLog/log$LogNameDATE.log
- Create A SystemD File
create a service file for the systemd on your system. This file must have .service extension and saved under the under /lib/systemd/system/ directory
#/etc/systemd/system
sudo nano /lib/systemd/system/shellscript.service
添加以下内容
[Unit]
Description=My Shell Script
[Service]
ExecStart=/usr/bin/script.sh
Restart=on-failure#always
RestartSec=3
[Install]
WantedBy=multi-user.target
关于python文件做成服务
[Unit]
Description=Dummy Service
After=multi-user.target
Conflicts=getty@tty1.service
[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/bin/dummy_service.py
StandardInput=tty-force
[Install]
WantedBy=multi-user.target
- Enable New Service
Your system service has been added to your service. Let’s reload the systemctl daemon to read new file. You need to reload this deamon each time after making any changes in in .service file.
sudo systemctl daemon-reload
Now enable the service to start on system boot, also start the service using the following commands.
sudo systemctl enable shellscript.service
sudo systemctl start shellscript.service
Finally verify the script is up and running as a systemd service.
sudo systemctl status shellscript.service
https://blog.csdn.net/weixin_43632687/article/details/123369843