I have an Ubuntu Server machine in which I need to run a Python script:
- at boot and then every 30 minutes
- with root permission
- without logging in
I searched on the internet and I found out that I should use sudo crontab -e
to edit my cron settings and add a line like this one:
30 * * * * python3 /myScriptPath/myScriptName.py
What I couldn't find is how to tell cron that my script must be run at boot and then every 30 minutes and not every hour at "hh:30" time.
Also, where should I store my script?
Write a control file and place it in
/etc/cron.d/myscriptrun
Do not make this file executable. It is a control file not a script.
Write a bash script and place it in
/usr/local/bin/myscript.sh
Make it executable
chmod a+x /etc/cron.d/bashscript
.The
&
starts the job in the background so the script will sleep for exactly 30 minutes. You can remove the&
and that changes the script to sleep 30 minutes after the job ends. Meaning jobs no longer start 30 minutes apart.Cron runs your job
You don't need to start the script, cron does that automatically at boot time. To monitor status use:
Your display will have
cron
at the top andsleep
at the bottom but will not haveeyesome
stuff in the middle, unless you are using that sunrise/sunset multiple monitor brightness/gamma transitioning software.To see when your python job runs at it's next 30 minute interval run an inquiry on the process ID of the
sleep
command (which is6575
in the example above):The time remaining is 55923 seconds divided by 60 seconds in a minute = 932 minutes before the job wakes up. To get a copy of
remaining_sleep_time
function see: