Open In App

Schedule Python Script using Windows Scheduler

In this article, we are going to schedule a python script using a windows task scheduler, i.e. make it launch automatically at a certain time or after a certain time period.

Before starting we need to know the following point:



Let’s implement with Step-wise:

Step 1: Make a python script

First, we’ll make the python script that we want to schedule. If you have already made the script, skip this section. If not, you can make your own python script or follow mine.



Here we made a python script that fetches a random inspirational quote image from a folder where I’ve saved a couple of them and displays it. You’ll need the following python packages/modules: tkinter, PIL, os, random.




# Python3 script to display
# random image quotes from a folder
  
# Importing modules
from tkinter import *
from PIL import ImageTk, Image
import os
import random
  
# Getting the file name of
# random selected image
name = random.choice(os.listdir(
    "C:\\Users\\NEERAJ RANA\\Desktop\\quotes_folder\\"))
  
# Appending the rest of the path
# to the filename
file = "C:\\Users\\NEERAJ RANA\\Desktop\\quotes_folder\\" + name
  
# Displaying the image
root = Tk()
canvas = Canvas(root, width=1300, height=750)
canvas.pack()
img = ImageTk.PhotoImage(Image.open(file))
canvas.create_image(20, 20, anchor=NW, image=img)
root.mainloop()

Remember to change the folder path according to the folder location on your system.

Now, there are two ways to schedule the script. The first method involves making a batch file, the other does not. If you don’t want to make a batch file, you can skip stepping 3.

Step 2(Optional): Make a batch file

A batch file is used to execute commands with the command prompt. It contains a series of commands in plain text you would normally use in the command prompt and is generally used to execute programs.

We are going to make a batch file to run our python script.

  1. First, open up any text editor.
  2. Next, enter the following lines in an empty file:
"C:\Python38\python.exe" "C:\Users\NEERAJ RANA\Desktop\GFG_Articles\scheduler\quote.py"
pause

The first string is the path to the python executable on your machine and the second one is the path to your saved python script. If you don’t know the path to your python executable, open up a command prompt and enter the following command: where python.

where command

If you see multiple paths, use any one of them. Also, change the path to your saved python script according to your system. The pause command is used to suspend the processing of the batch program and wait for the user’s input. And lastly, save this file with a .bat extension.

Step 3: Scheduling the script

If you made a batch file

If you didn’t make a batch file

Now, at your chosen time, your script will execute.


Article Tags :