While trying to schedule the python script, the first mistake we do is by trying to go to the virtual environment folder and then trying to activate the virtual environment through the script. But we can use the absolute path directly
1. Create the bash file runmypythonscript.sh
Do not do things like changing directory, activating virtual env. These commands won’t work
#!/bin/bash
# cd /home/mypc/awesomeproject
# source venv/bin/activate
# python myawesomepythonscript.py
We can directly use the absolute path to the python
/home/mypc/awesomeproject/bin/python myawesomepythonscript.py
If we don’t have the virtual env, python path can be found using the following command and use that absolute path
which python
For the Virtual environment, the python path could be found by first activating the virtual environment and then running the which python command. The path of the virtual environment is usually
virtualenvfolder/bin/python
For python3
virtualenvfolder/bin/python3
2. Update the permissions to run for all users.
chmod a+x runmypythonscript.sh
If needed use the sudo command and enter the user password
sudo chmod a+x runmypythonscript.sh
3. Open the crontab using the following command
crontab -e
If no editor is selected, you can select the desired editor. The selected editor can be changed later by the select-editor command
4. For running the script every 15 minutes. Enter the following at the end.
*/15 * * * * /home/mypc/run/runmypythonscript.sh >> /home/mypc/logs/cronlogs.log 2>&1
To confirm the time of cron jobs, you recommend using the following website.