Sometimes we want our script to run at a specific time or a specific number of times. We can automate this task so we don’t need to run the script manually. Windows provides a software allied task scheduler that will run our script at a given time.
- Works only on Microsoft Windows operating system
- Your Computer needs to be switched on at the scheduled time
- Doesn’t not imitate Server like – specific time execution. So in order to run a code at any time without the hassle of doing it self (switching the computer on) – you need to do using a Server (execution of script on server)
Steps to use the Windows Task Scheduler
Let’s get right into the steps to schedule the execution of Python scripts right away. Follow through and let us know if you have any questions later! We’ll make use of the Windows task scheduler for easier setup.
1. Open the task scheduler
Open the task scheduler application on your computer by searching for Task Scheduler in the start menu.
2. Create a new task
Next, create a task in the task scheduler by right-clicking on the Task Scheduler (Local).
3. Name the task
Add a name so you can identify it later.
4. Create a new action for our script
Switch to the “Actions” tab and add a new action. This is where the real stuff happens.
5. Run python script
To run the python script automatically using Windows scheduler we need to follow the below steps in our code:
- We need the path of our python installation which we can find by running the following python code.
import sys print(sys.executable)
- We’ll paste this location in box number 1 of our Windows Scheduler action
- In the box number 2 we’ll pass the name of the script file (python file)
Ex: python_sample_file.py or a.py
- In box number 3 we’ll pass the path of our Python executable (python file)
6. Create a trigger for the Script
A trigger means an event that causes our script to run. For example, we can specify a time on which our script will get executed. It provides options like what day, what time, how many times, for how long our script should get executed.
Hence, you’ll need to enter all the required details of it.
For our program, we’ll set a specific time that will trigger our following script to execute:
print("Hi, this is scheduled message")
On successful creation of our Windows Task Scheduler and upon the trigger of the python script file, the script is executed and the output is displayed as follows in the Windows Command Prompt:
Hope you have learned well how to run your python script file at any desired time. Scheduling a task, which is quite useful in attaining automation of your script file.