When you say "I have created a service", I wonder if you mean "I have created a shell script" or something similar. As creating a service would involve writing a .service
file, which is 90% of the challenge in performing the task.
So, for the sake of this answer, I'm going to assume that you've created a shell script called query_db.sh
. The next step will be to create the .service
file, then enable it.
Here is how you create a service:
- Open Terminal (if it's not already open)
- Create a new file for the service. I will call mine
query_db.service
:
sudo vi /etc/systemd/system/query_db.service
Note: Feel free to use any text editor you wish. The use of vi
in this example is neither a suggestion nor an endorsement. It's just a force of habit.
- Paste the following into the new file, editing the relevant values where appropriate:
[Unit]
Description=Do Some Query
[Service]
User=dheeraj
WorkingDirectory=/home/dheeraj/scripts
ExecStart=/home/dheeraj/scripts/query_db.sh
Type=simple
TimeoutStopSec=10
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Note: Be sure to change the User
, WorkingDirectory
, and ExecStart
values to something correct. The other items can remain untouched if you are unsure of how to configure them.
- Verify that the script file is executable:
sudo chmod +x /home/dheeraj/scripts/query_db.sh
- Reload the
systemd
daemons:
sudo systemctl daemon-reload
- Enable your daemon:
sudo systemctl enable query_db
- Start your daemon:
sudo systemctl start query_db
That's all there is to it. You can now check the status of your service with:
sudo systemctl status query_db
And, of course, you can stop your service with:
sudo systemctl stop query_db
If you prefer to use the shorter commands, swap the action with the service name:
sudo service query_db status
sudo service query_db stop
That's really all there is to it.