Cron Job Not Running on Ubuntu 20.04.2 LTS
I have created a Cron job to run a script that checks if a process is running, in case it does it just print that the process is running, if not it prints out the process is not running and restart the process:
#!/bin/sh
SERVICE="start_server.py"
if ps -ef | grep "$SERVICE" | grep -v grep >/dev/null
then
echo "start_server.py is running"
else
echo "start_server.py stopped"
python2.7 start_server.py &
fi
As user Ubuntu I created the following cron job by running - crontab -e
* * * * * /home/ubuntu/mislaka/check_process.sh 2>&1 /home/ubuntu/mislaka/script_log.log
For some reason, it is not working or writing the output to the log file.
Tried restarting cron service, tried creating the cron job as root, changed all the permission and the user who is running the script yet nothing is working.
The script if I run it by itself works as expected.
Ubuntu Version:
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 20.04.2 LTS
Release: 20.04
Codename: focal
Thanks in advance
Jobs run through cron
, or systemd
startup scripts aren't run in the same runtime environment that you have on your desktop. systemd
startup scripts are run as root
. None of your PATH
changes, or other environment variable settings are automatically propagated to your cron
job. For example, there's no $DISPLAY
, so GUI programs need special treatment (read man xhost
).
One can set environment variables for all one's cron
jobs in the crontab
file
Read man 5 crontab
.
Look at the results of echo "=== id ===";id;echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias
in each of your environments.
Since the command
part of the crontab
line is, by default, interpreted by /bin/sh
, which has a simpler syntax than /bin/bash
, I recommend having command
be a call to a bash
script (executable, mounted, starts with #!/bin/bash
) which sets up the environment, then calls the desired program.