What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Schedule Script with Python Task Scheduler in Windows

  • Feb 03, 2023
  • 5 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
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:

$ pip install scheduler

 

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:

$ python gmail_script.py

 

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:

@echo off
python <path-to-the-file>

 

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.

For Linux:

Run the following commands:

$ sudo cp -i <path-to-the-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 - 24x7 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.