Automation of Python program execution
Automating and running a Python program on a recurring or scheduled basis can be done in a number of ways depending on the operating system and environment it is running in. Below I explain how to do it on both Windows and Linux, and some additional options if you want more control or flexibility.
1. Automate on Windows with Task Scheduler
- Save your Python script, for example, as bitcoin_rsi.py.
- Open Task Scheduler from the start menu.
- Click "Create Task" in the right panel.
- On the "General" tab, give your task a name (for example, "Run Bitcoin RSI").
- On the "Triggers" tab, click "New..." and set the schedule or frequency (for example, hourly or daily).
- On the "Actions" tab, select "New...", choose "Start a program", and in the "Program or script" field, type the path to your Python file. Make sure you have python.exe set in your PATH.
- For example:
C:\path\python.exe
C:\path\to\script\bitcoin_rsi.py
- Save the task and it will automatically run on the schedule you set.
2. Automate on Linux with cron
- Save your Python script, for example, as bitcoin_rsi.py.
- Open the terminal and type:
crontab -e
- This will open the crontab file for the current user. Here you can add the schedule to run your script.
- To run the script every hour, you can add a line like this:
Recommended by LinkedIn
..../usr/bin/python3 /path/to/your/file/bitcoin_rsi.py
- This will run the Python script every hour on the hour. Make sure the path to python3 and your Python file are correct.
- Save and close the file. Now cron will run your script automatically.
3. Automate using a `.bat` file on Windows
If you prefer to use a .bat file to run the script and then schedule it:
- Create a text file and change its extension to .bat, for example run_bitcoin_rsi.bat.
- In the .bat file, type the following command:
@echo off
python C:\script\path\bitcoin_rsi.py
pause
- Save the file.
Follow the same steps as before to create a task in Task Scheduler, but this time select the .bat file instead of the .py file.
4. Use a cloud solution: Heroku, AWS Lambda, or similar services
If you want to automate the execution of your script in the cloud, you can use platforms such as:
Each of these platforms has its own task scheduling system and can be ideal if you don't want to rely on a local environment.
5. Using an infinite loop with time.sleep() inside the script
Another simpler (albeit less efficient) option is to have the script run continuously and pause at intervals.
With this approach, the script runs continuously and performs the task every hour. You can run this script in any environment and leave it running.
Summary