Simple Windows Task Scheduling (With a Bit of Python)

In Windows, there is the graphical tool Task Scheduler, which allows to, well, schedule tasks. It’s nice, but it’s not scriptable. So we go for the command line here.

First, we write a small Python program, which represents the actual work to do. In this case, it writes a live log, i.e. each time it runs, it adds a line of text to a file. This file could be monitored, e.g. to check if a server machine is up and running. Of course, its functionality could be extended.

import time
livelog = open("live.log", "at")
message = time.strftime("Rufus is alive at %Y-%m-%dT%H:%M:%S\n", time.localtime())
livelog.write(message)
livelog.close();

(Save as send_live_signal.py)

In order to execute the Python program, we create a Windows batch file. This allows us to control the environment under which the Python program runs. Gives flexibility, at least.

C:
cd C:\sw\tutorial
set PATH=c:\sw\Python27;%PATH%
python send_live_signal.py

(Save as execute_task_1.bat)

In order to gain more flexibility, we can add another layer of batch files, which allows us to split up tasks.

C:
cd \sw\tutorial
call execute_task_1.bat
call execute_task_2.bat

(Save as dojob.bat)

But now to some serious scheduling. In Windows, the command line program with the lovely name schtasks is responsible for creating, querying, and deleting tasks, and does even more. A simple call to this program (from another batch file, for example) creates a livelog that is written every minute:

schtasks /Create /SC MINUTE /TN Livelog /TR c:\sw\tutorial\dojob.bat

You can schedule the tasks in a variety of manners. For example, a job can be run twice every week, at 4 o’clock in the morning, the best time for some action:

schtasks /Create /SC WEEKLY /D TUE,SAT /ST 04:00 /TN PerformAction /TR c:\sw\tutorial\dojob.bat

You can specify complex schedules, and there is a little bit of syntax to master. Consult the help: schtasks /Create /?, which is quite good. Creating tasks is fine, and now we would like to see if they are actually running. schtasks will tell you whether a task of yours is active and when it will run the next time:

schtasks /Query /TN Livelog
schtasks /Query /TN PerformAction

If you get tired of a task, just delete it:

schtasks /Delete /TN PerformAction

Advertisements
This entry was posted in Software, Windows. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s