Issue
I need a python script to run every 2 minutes. Is there a possible way to run script.py
FROM a python script?
I would want this added to the crontab:
*/2 * * * * * /usr/bin/python3 /path/to/script.py
Reminder: I do NOT want to use crontab -e. I specifically want to create a cronjob from a python script.
Solution
I read about you dont want to use crontab but i would like to know why and I would give my solution with crontab. The solution that @Kushim propposed is indeed a bad approach since you are not only creating the execution of 2 minutes "by hand" but also you do not get any information or output of your script unless it raises an Exception. To define a job each 2 minutes you should first execute in your terminal:
crontab -e
and add this at the end:
*/2 * * * * ./run_script.py >> crontab.log 2>&1 #2>&1 redirects errors to stdout
So run_script.py will run each 2 minutes. Now, to call the other script from run_script.py you can write this in run_script.py
import subprocess
result = subprocess.run(['python3', 'other_script.py'], stdout=subprocess.PIPE)
print(result.stdout)
Whether your other_script.py raises and exception or not it will be managed by subprocess and it will be written in a log file to check the output.
Answered By - Antonio Bri Answer Checked By - Marilyn (WPSolving Volunteer)