On my raspberry pi device with ubuntu 20.04 , when I manually run the start.py code after reboot the device
within the folder /home/okay
python3 start.py
both scripts are running one after the other.
But when I put this code in @reboot in crontab,
@reboot sleep 300 && python3 /home/okay/start.py
only the first script runs, the second one does not.
the py script is below
import os
os.system ("python3 /home/okay/avadot.py & ")
os.system ("python3 /home/okay/main.py &")
The reason I wrote the code with os.system is that both py files run in a while True: loop every 10 minutes.
Therefore, it is not possible to start the other when one is finished, both must start working at the same time.
2
Answers
First things is cron needs full paths to the executables you want to use.
You can find them with
command -v <cmd>
.I guess you’re looking for something like
Then, the script you wrote runs sub processes. If you look at the documentation of
os.system()
, you can read:So you should probably do that:
Which will start both processes, but note it’s a bad idea starting processes and without plans for their termination (see
Popen.wait()
orPopen.poll()
).It doesn’t seem to make much sense to use Python for the
cron
job at all.os.system("cmd &")
will runcmd
as a background job of the shell it spawns, but the shell will hang around until the background job finishes. You can detach by various means, but the simplest solution is to run both jobs from the same shell, and not use Python at all.If you desperately want to spend one process more, you can run this from Python:
or refactor your code so you can
import
these two scripts and run them withmultiprocessing
.Returning to the simpler proposal, you can launch both processes from one
cron
jobbut
cron
already runs in the background, so you could split it up intoThere may be additional complications; one common beginner conundrum is attempting to run tools which require a graphical display or user interaction, which of course are not trivially available from
cron
at all. Perhaps see CronJob not running for more information and troubleshooting tips.