Reputation:
I have a few Discord bots written in Python that will stop for whatever reason after a few hours. I want a way to monitor them and restart them if they go down. I've already looked for a few solutions including a bash script, crontab, and systemd, but none of them seem to be working for me.
Even with a simple while true bash script, it will go down for some reason. The crontab won't run because of what I assume are environment issues, and apparently systemd is only for services?
All of the python scripts are located in /home/username/folder/script.py
I would also like to be able to easily pause the service that restarts the scripts, because occasionally I will have to update the code with git.
Upvotes: 4
Views: 7210
Reputation:
I figured out how to solve my problem with systemd.
First navigate to:
/etc/systemd/system
Then create a new service as root:
sudo nano example.service
Make your service file like this:
[Unit]
Description=Restarts example.py if it closes
[Service]
User=your username
WorkingDirectory=/directory/of/script
ExecStart=/usr/bin/python3 /directory/of/script/example.py
Restart=always
[Install]
WantedBy=multi-user.target
Then type this in to have systemd reload the service files.
sudo systemctl daemon-reload
Then you can start your service:
sudo systemctl start example.service
Finally, check the status of your service:
sudo systemctl status example.service
Upvotes: 5
Reputation: 21
monit will suit your needs, you can configure it to monitor your python scripts and restart them upon failure.
it's kinda quick to configure
Reference : https://mmonit.com/monit/
Upvotes: 0