- How To Schedule Python Scripts to Automate Tasks using Windows Scheduler on Windows 10
- Step 1: Create your Python script.
- Step 2: Create Batch File to Run the Python Script
- Step 3: Schedule Python Script using Windows Scheduler
- Schedule Script with Python Task Scheduler in Windows
- Task Scheduler in Python
- Automating Opening Gmail every day
- Automating the script
- Conclusion
- FavTutor — 24×7 Live Coding Help from Expert Tutors!
- How to Schedule Python Script using Windows Scheduler
- Steps to Schedule Python Script using Windows Scheduler
- Step-1: Prepare the Python Script
- Step-2: Save the Python Script
- Step-3: Create a Batch File to Run the Python Script
- Step-4: Schedule the Python Script using the Windows Scheduler
How To Schedule Python Scripts to Automate Tasks using Windows Scheduler on Windows 10
In this post, I will go over the steps necessary to schedule a Python script using Windows Scheduler. This can be particularly useful if you want to re-run a particular programme at a prescribed time, for example, for a web scraper.
For the purpose of this post I will further assume that you have Python set up and running on your machine. For everything else, please follow the step-by-step guide below:
Step 1: Create your Python script.
This should be self-explanatory. Let’s assume we want to run the following script called my.py , which does nothing but print today’s date:
#################### # Content of my.py # #################### import datetime # Get date and time todaysDate = datetime.datetime.today(); # Change display format (optional) todaysDate = todaysDate.strftime("%Y-%m-%d %H:%M:%S") # Print print(todaysDate)
Now save your script! In my case, I’ll simply save the Python script on my Desktop.
where should be replaced with your Windows username.
Step 2: Create Batch File to Run the Python Script
First, open Notepad and generate the following generic structure:
In our example, the batch file will read as follows:
"C:\Users\\AppData\Local\Programs\Python\Python38\python.exe" "C:\Users\\Desktop\my.py" pause
Note: In case you want your batch file to run Git to automatically add, commit and push to GitHub, you will need a couple of extra lines of code which I discuss in this blog post.
Next, save the file with the ‘bat’ file extension; we’ll call our file run_mypy.bat for now.
Finally, go ahead and check if the batch file triggers your Python script correctly. For this, you only have to double-click run_mypy.bat . If everything has worked out, a command prompt should open now containing the following pieces of information (including the date and daytime, which in this case is 2020-12-16 12:12:12):
C:\Users\\Desktop>"C:\Users\\AppData\Local\Programs\Python\Python38\python.exe" "C:\Users\\Desktop\my.py" 2020-12-16 12:12:12 C:\Users\\Desktop>pause Press any key to continue . . .
Step 3: Schedule Python Script using Windows Scheduler
- Open Control Panel and search for Administrative Tools .
- Select Task Scheduler . There, select option Create Basic Task. in the right panel.
- Give your Task a name (in this case we’ll name the task ‘Run mypy’), and now define how often and when you want the task to be triggered. This step is rather self-explanatory.
- Once you have configured the trigger for your job to your satisfaction, click next and define the Action which you want the scheduled task to perform. In our case we want to Start a program .
- Click Next and then on Browse . Then navigate to where your batch file sits. In our case C:\Users\\Desktop\run_mypy.bat .
- IMPORTANT: If you are planning on saving/appending data that you obtain from running the Python script, make sure you also provide the location of your application folder in Start in (optional) . This allows the Scheduler to access all of the relevant elements (files, folders etc.) of your project. In our case, this would be C:\Users\\Desktop\ .
- Click Next again and the final screen will provide a summary of the new task you have just created. You can always navigate back and change its configuration. Once you’re happy with your result click Finish and you’re done!
- To check if the task you created works, access the Task Scheduler Library (left panel in Task Scheduler), select the task from the list of created tasks (middle panel), right-click and then click on Run . A terminal window should open and return the same result as when double-clicking run_mypy.bat .
This last step completes this tutorial. If you want to learn more about Windows Task Scheduler, check out the online documentation.
Schedule Script with Python Task Scheduler in Windows
Python is a brilliant language when it comes to automating away repetitive and boring tasks because of its simple syntax and extensive libraries that abstract complexities and make everything easy to use. One such library we will explore in this article is Scheduler.
In this article, we are going to learn how to create a Task Scheduler in Python. But before we get into the code part, let us first understand the importance and usefulness of task scheduling.
Task Scheduler in Python
Task scheduling allows you to run a task at a particular period of time in regular intervals if necessary. Scheduling is essential in cases such as fetching data from a database regularly, training machine learning models when there’s an influx of new data, or just automating daily tasks such as opening Gmail on the browser every morning.
Python’s Scheduler module provides an easy way of scheduling the execution of certain tasks at specific times. The tasks can be executed once or repeatedly. This module is not built-in and needs an installation. Here’s how you can install the scheduler module:
Running the above command in the terminal will install the module fetching it from the PyPI repository. If the module’s installed correctly, you should see an output similar to this:
Collecting scheduler Downloading scheduler-0.8.3-py3-none-any.whl (33 kB) Collecting typeguard>=2.6.0 Downloading typeguard-2.13.3-py3-none-any.whl (17 kB) Installing collected packages: typeguard, scheduler Successfully installed scheduler-0.8.3 typeguard-2.13.3
Now that the module is successfully installed, let us explore task scheduling. Automating a simple task like opening Gmail every morning is a great place to start as it covers the fundamentals of task scheduling while also being useful in daily life.
Automating Opening Gmail every day
Before we schedule the task of opening Gmail every day, we should first write the code for the task. So, we should write a function that opens the browser and opens the URL of “https://mail.google.com”.
We can do that through the module web browser. The web browser module provides functions to access any supported web browser on a computer and open any URL through the browser. This module is built-in and requires no pip installation. A method that opens Gmail should be as follows:
import webbrowser def open_gmail(): url = 'https://mail.google.com' webbrowser.open(url)
Now that we have the method defined, let us schedule a task of running this method every morning at 10:00 AM.
import schedule import time schedule.every().day.at("10:00").do(open_gmail) while True: schedule.run_pending() time.sleep(1)
We are importing the schedule module and we are calling the function every(). There are numerous attributes for every() method such as month which will result in every month, and day which will result in every day. We picked .day and then used the .at attribute to pass the time of “10:00” which is in 24-hour time format.
We then called the .do() function and passed the function we defined earlier “open_gmail”. After that, we created a while loop which has the condition of a boolean value “True” meaning the loop is an infinite loop that will run as long as the script is running, and under the loop, we called the run_pending() function in schedule essentially running the earlier written statement.
The next line contains “time.sleep(1)” which is running the sleep method from the time module. The sleep function with parameter 1 freezes the runtime for a second. This is used to avoid any errors and optimize the code for a better flow.
A script should be created with all the code from above and it should be run from a terminal so that the process runs all the time without the need of an IDE. This can be done in the command prompt or terminal in the directory of the script with the following command:
So, this should essentially start a scheduled process that opens the browser with the Gmail URL every morning at 10:00 AM. Here’s the entire code for the script gmail_script.py’:
import schedule import webbrowser def open_gmail(): Url = 'https:mail.google.com' webbrowser.open(url) schedule.every().day.at("10:00").do(open_gmail) while True: schedule.run_pending() time.sleep(1)
Automating the script
But a problem arises in this method of running the script. Every time the system is restarted, the script needs to be run again. To avoid this, we can schedule running a python script on startup.
For Windows:
This can be done by creating a .bat file in the location “%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup for windows”. The .bat file, say gmail.bat, should contain the following:
Another method of scheduling a python script in Windows is via the Windows Task Scheduler. To create a Task in the task scheduler, go to the Actions tab and create an action, pick the action “Start a program” and enter the path to the file in “Program/script”.
Then, the name of the file in “Add Arguments (optional)” and the path to the folder containing the file in “Start in (optional)” and click OK. Then, go to triggers and select the option “daily” and click OK. This should run the script all the time.
Run the following commands:
$ sudo cp -i -file> /bin $ sudo crontab -e
And add the following line and save it:
@reboot python /bin/test_code.py &
After this is done, the script will run every time on startup, and every morning at 10:00 AM, a browser will open your Gmail. We have explored and successfully scheduled a task using Python and the scheduler module.
Conclusion
Following this tutorial, one can automate many other repetitive tasks such as fetching stock data daily, loading the data from a database, regular training of machine learning models, etc. Now you know how to schedule tasks in Python for Windows and Linux.
The fundamental understanding of the scheduler module, time module, and the understanding of functionality of a script that’s always running is the knowledge that will help one as a programmer for the rest of their life.
FavTutor — 24×7 Live Coding Help from Expert Tutors!
About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.
How to Schedule Python Script using Windows Scheduler
In this guide, you’ll see the steps to schedule a Python script using Windows Scheduler.
Steps to Schedule Python Script using Windows Scheduler
Step-1: Prepare the Python Script
For example, let’s suppose that the goal is to display ‘Hello World!’ each day at 6am.
Here is the Python script to be used for our example (you may use another Python script based on your needs):
import tkinter as tk root= tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 300) canvas1.pack() label1 = tk.Label(root, text='Hello World!') canvas1.create_window(150, 150, window=label1) root.mainloop()
Step-2: Save the Python Script
Once you’re done writing the script, save it as a Python file (where the file extension is .py):
For instance, let’s save the file as hello_world.py under the following path:
Step-3: Create a Batch File to Run the Python Script
To start, open Notepad, and then use the following template:
"Path where your Python exe is stored\python.exe" "Path where your Python script is stored\script name.py" pause
- The path where the Python exe is storedis:
“C:\Users\Ron\AppData\Local\Programs\Python\Python39\python.exe” - The Path where the Python script is storedis (see step-2):
“C:\Users\Ron\Desktop\hello_world.py”
Here are the paths in the Notepad (you’ll need to adjust those paths to fit your instances):
"C:\Users\Ron\AppData\Local\Programs\Python\Python39\python.exe" "C:\Users\Ron\Desktop\hello_world.py" pause
Finally, save the Notepad with your file name and the “.bat” file extension:
file_name.bat
For example, let’s save the Notepad as:
run_python_script.bat
After you saved the Notepad, a new batch file (called run_python_script) would be created at the specified location:
Step-4: Schedule the Python Script using the Windows Scheduler
In order to schedule the Python script using the Windows Scheduler:
- Open the Windows Control Panel and then click on the Administrative Tools
- Double-click on the Task Scheduler, and then choose the option to ‘Create Basic Task…’
- Type a name for your task (you can also type a description if needed), and then press Next. For instance, let’s name the task as: Run Hello World
- Choose to start the task ‘Daily‘ since we wish to run the Python script daily at 6am. Also specify the start date and time (6am for our example)
- Select, Start a program, and then press Next
- Use the Browse button to find the batch file (run_python_script.bat) that runs the Python script. In our case:
Finally, click on Finish, and you should be good to go. From this point onward, you’ll be greeted with ‘Hello World!’ everyday at 6am.