There are multiple ways to schedule a Python program, task, event or script in Windows Operating System.
In this Python tutorial we will demonstrate various different methods that can be helpful for scheduling tasks or events:
This is pretty simple to achieve but there are some details to consider.
1- Let’s create a really simple Python program.
I’ll simply print Hello World! But also, I’ll do a little trick here by using time library as well.
If we don’t create a delay function program will run in a tiny fraction of a second and disappear so it will be hard to observe. So, let’s add a 10 second sleep time after the print function.
Skill LevelUpper-Intermediate
Modules.Dispatch
.Connect, .GetFolder
.NewTask
win32com, os
win32com.client
import time
print("Hello World!")
time.sleep(10)
We have a simple but decent program for demonstration already. Let’s move on to saving file as .py step.
2- Saving a file as .py file is easy. One needs to simply navigate to file tab in any IDE.
From there,
Another way to create a .py file is simply using Notepad from Windows, especially when the code is this simple it’ll work like a charm.
However, there is something you gotta pay attention to:
You gotta make sure save as type: section of the window is at “All Files(*.*)” otherwise whatever you type Notepad will add .txt to the end of the file and you will end up with something like: test.py.txt.
We don’t want that, we want test.py only (Replace test with whatever name you want). So just make sure type is set to All Files like below.
Saving .py file with Notepad3- Now, it’s time to schedule the application we created. Simply Navigate to Start of Windows and type Task Scheduler. Then, Go ahead and open the app.
Task Scheduler3- Now, it’s time to schedule the application we created. Simply Navigate to Start of Windows and type Task Scheduler. Then, Go ahead and open the app.
Task Scheduler - Create TaskYou’ll see Actions section on the right side. Click Create Task to create a new task.
A new window will pop up and you’ll need to take care of 3 things there. This is the final step. 3rd step is important to understand and get it right for the program to execute properly when it’s due.
So first step, as well as second step, is I believe self-explanatory. For trigger, just create new and maybe choose a one time trigger for a couple minutes later for demonstration. If your current time is 10:00pm you can try 10:05pm.
On the final step, when creating trigger
So, basically what’s happening here is that you’re scheduling Python.exe to run as a program and then you’re passing your own program, script, task, code or whatever you wanna call it as an argument to Python.exe.
Since, we have created a 10 second delay in the code. Hello World! will beautifully appear on the screen for 10 seconds. Plenty of time for you to feel accomplished.
Task Scheduler - Task is executed on timeAs a practice, I recommend doing this whole operation by yourself after reading this Python tutorial. Also, for the first time you can save your code with print(“Hello World!”) only to observe the phenomenon that we’ve mentioned above. In that case your code will flash for a tiny moment and disappear before you have a chance to read it.
How to Automate Task Scheduling w/ Python (pywin32 library)We can directly connect to Windows Task Scheduler from Python via pywin32 library. This can be very powerful if you want to finish everything from inside Python.
Another time it can be very useful is when your Python program has a GUI and you don’t want the user to go to Task Scheduler separately to schedule events.
Think applications like
So, how are we going to achieve this noble goal? By using pywin32 library. Below, you can see an example that you can actually directly modify and implement. This application is consisted of 6 basic steps:
#Import Libraries
import datetime as dt
import win32com.client
#Connection to Task Scheduler
task = win32com.client.Dispatch('Schedule.Service')
task.Connect()
root_folder = task.GetFolder('\\')
newtask = task.NewTask(0)
# Trigger
set_time=dt.datetime(2020,9,4,18,44,0,500000)
TASK_TRIGGER_TIME = 1
trigger = newtask.Triggers.Create(TASK_TRIGGER_TIME)
trigger.StartBoundary = set_time.isoformat()
set_time variable is used to define the exact time task is being scheduled to. So, you can adjust the first line accordingly.
Alternatively, you can schedule time to something like “5 minutes from now” or “2 hours from now” or “same time tomorrow”. Just refer to this code snippet for that:
set_time = dt.datetime.now() + dt.timedelta(minutes=1)
# Action
TASK_ACTION_EXEC = 0
action = newtask.Actions.Create(TASK_ACTION_EXEC)
action.ID = 'DO NOTHING'
action.Path = r'C:\Anaconda3\python.exe'
action.Arguments = r'C:\Users\ABC\Desktop\new3.py'
action.Path is the path to your python.exe file. If you have Anaconda3 installed it should be something like above, you might want to double check your Python or Anaconda installation.
action.Argument is the path to whatever .py file you’re trying to schedule.
Basically we’re passing the .py file as an argument to python.exe program. python.exe is the actual program being scheduled here and program (or task or code or event or script) in the .py file is being passed as an argument.
You can adjust the Task Description according to your task.
# Parameters
newtask.RegistrationInfo.Description = 'Python Task Test'
newtask.Settings.Enabled = True
newtask.Settings.StopIfGoingOnBatteries = False
Finally, task gets saved in this step,
# Saving
TASK_CREATE_OR_UPDATE = 6
TASK_LOGON_NONE = 0
root_folder.RegisterTaskDefinition(
'PTT', # Python Task Test
newtask,
TASK_CREATE_OR_UPDATE,
'', # No user
'', # No password
TASK_LOGON_NONE)
That’s all. This code should work from the get go with a few basic adjustments. You can find the full code on HolyPython Github Repository here.
If you’re interested in combining this knowledge with a GUI application you created with Python you can check out this tutorial about GUI applications with Python.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4