Scheduling a Python script or model to run at a prescribed time

At the Spatial Analysis and Geoprocessing island at this year’s user conference, several folks asked us about running a Python script or ModelBuilder model at a prescribed time — usually in the early morning when their computers are bored and just waiting for something to do. We thought it would be good to make a post about this and to share some tips.

The first place to start is with the help topic Scheduling a Python script to run at prescribed times. This topic is kind of buried in the help system so it’s easy to miss. The meat of this topic shows you how to launch Window’s Task Scheduler on various operating systems (Windows 7, XP, and so on). The screenshot below shows the Task Scheduler on Windows 7. There’s a lot stuff you can do with the task scheduler and you’ll just have to play around with it and read the Windows help. The Actions pane, on the right, has the Create Basic Task action, and this is the place to start.

Clicking on Create Basic Task opens a wizard where you define the name of your task, the trigger (when it runs), and the action (what program to run). The screenshot below shows the Action tab where you specify the name of your Python script to run as well as any arguments to the script.

The Action tab is where we have a few tips, as follows.

Run the Python executable with arguments

To ensure that your Python script will run regardless of the login account that the schedule task uses, and to avoid any confusion about which version of Python is used in mixed environments (64bit or 32bit), we recommend that you run the Python executable with the name of your Python file as an argument to the executable.

Suppose the script you want to run is E:\My Instead of running the script directly, instruct the task scheduler to run python.exe with the script as an argument. For example:

C:\Python27\ArcGIS10.2\python.exe "E:\My"

The location of python.exe depends on your install. If you don’t know where it is, you can discover its location; copy and paste the following code into a new Python script then execute the script. The script will print the location of python.exe as well as other information about your Python environment.

import sys
import platform
import imp

print("Python EXE     : " + sys.executable)
print("Architecture   : " + platform.architecture()[0])
print("Path to arcpy  : " + imp.find_module("arcpy")[1])

raw_input("\n\nPress ENTER to quit")

After determining the location of python.exe, this is what is entered in the Action panel of the task scheduler:

If there are additional arguments (parameters) to your script, provide them after the path to your script. For example, the following command line executes a Python script that takes two arguments; the path to a feature class and an integer.

C:\Python27\ArcGIS10.2\python.exe "E:\My Scripts\" c:\gisWork\gdb.mdb\counties 10

We typically recommend writing scripts so that they take arguments like the above example rather the hard-coding dataset paths or values within the script. However, this is one case where hard-coding paths and values in your script works to your advantage; rather than changing argument values in the task scheduler, it’s easier to just edit your script to use different paths or values.

If you’re familiar with .bat files in Windows, you can have the task scheduler run a .bat file that in turn runs your script with arguments. The contents of the .bat is the single command line shown above.

Remember that if any of your arguments contain spaces, you need to enclose the argument in double quotes. In the above example, E:\My Scripts\ contains a space, so double quotes are required.

Running models at a prescribed time

A common misconception is that in order to run a model as a Python script, you must first export the model to a Python script. Geoprocessing is designed so that models are tools, just like all the tools delivered with the ArcGIS.  That means you can run your model within Python just like any other geoprocessing tool.  All you need to do is import the toolbox containing your model using the ImportToolbox function, then run your model within Python.

For example, the model to the left imports a .gpx file to a geodatabase, adds a field, calculates it to the current date and time, then appends all those features into a “master” feature class.

To run this model on a schedule, all that’s needed is to execute the model within a script. Here’s the Python script to run the model:

import arcpy
import os
from datetime import datetime

# Import the toolbox containing the model.  This toolbox
#  has an alias of "gpxtools"

# Run the model.  The model has two parameters, the input
#  .gpx file and the feature class to update

# Now that the input gpx file has been processed, rename it
#   to have the date and time.
          r"c:\ftp\inbox\datadrop{}.gpx".format(datetime.strftime(, "%Y%m%d"))

Advanced options

The Create Basic Task wizard allows you to set basic properties of the task. Once the task is created, you can examine its properties and refine its triggers and actions. For example, you can have your task run every five minutes for three hours. You can set up a task with advanced options using the Create Task action.

Start simple

When I started writing this blog, it had been a long time since I messed around with scheduled tasks, so I started with a simple script that wrote information to a log file. I scheduled it to run every minute for ten minutes so I could test changes to the script soon after I made them. It was a great way to test and understand how scheduling worked before committing to running the “real” script. Here’s my simple script:

import sys
import platform
import imp
print "Importing arcpy... this may take a moment\n"
import arcpy

# Open a log file to write to
f = open(r'E:\schedule.log','w')

# Write date/time
f.write(time.strftime('%x %X'))

# Test receiving of arguments/parameters via arcpy
f.write("Parameter 0 : " + arcpy.GetParameterAsText(0) + "\n")

# Python info
f.write("Python EXE : " + sys.executable + "\n")
f.write("Architecture : " + platform.architecture()[0] + "\n")
f.write("Path to arcpy : " + imp.find_module("arcpy")[1] + "\n")

Ghislain Prince contributed to this post

This entry was posted in Analysis & Geoprocessing, Migrate, Python and tagged , , . Bookmark the permalink.

Leave a Reply


  1. cmlosaria_gis says:

    cool post!

  2. mvalderrama says:

    Thanks, very good explanation.

  3. raj_philly says:

    Thank you for the blog! This is really helpful. You might want to end the f.close() at the end so the text is saved before closing.

  4. Dale Honeycutt says:

    Below is a link to a forum post that describes and solves a data access problem in a scheduled task. If your scheduled task is having data access problems (that is, it can’t find the datasets it needs), have a look at the post. It has to do with mapping external drives to a drive letter (for example, “Y:” is mapped to “//somemachine/gis_data“)

    Here’s the link: Windows Scheduler Python issue

  5. alexroma says:

    In mid-July 2013 I created a script “C:\Python27\ArcGIS10.1\python.exe ……..” that worked perfectly fine and I left it alone to work silently in the background. In mid-August I noticed that I was missing a bunch of results during the last two weeks. After a long search I realized that ArcGIS 10.2, that I installed during that period, caused the issue. I totally forgot to update the “10.1″ line to “10.2″ in that script. Beware!

    • Dale Honeycutt says:

      Great point. That’s one advantage to running the script directly (instead of “C:\Python27\… C:\mystuff\myscript”, just “C:\mystuff\myscript” — you’re not dependent on the location of Python. But then again, when Python doesn’t start for whatever reason, the fallback is to run Python (“C:\Python27\…”). It’s a trade-off.

      • Curtis Price says:

        This works, and forces 32-bit python (important if you need to access personal gdb, etc). If you have background geoprocessing installed, .py is associated with x64 Python.)

  6. ghopkins says:

    Hi Dale,
    Thanks for your post! I’m struggling to get this to work though. My script will work if I run it from Python Win (only after right clicking and running as Administrator… I’m running it on Windows Server 2008) but when I try to run it from Task Scheduler it just doesn’t work. It says it runs successfully but it’s clearly not working (I’ve told it to run this task as the local Administrator). I’ve tried running the script directly and by your suggestion about to run python.exe and then run the script as an argument. Do you have any ideas as to what I’m doing wrong?


    • Dale Honeycutt says:

      So sorry — I just discovered your comment. Did you find a solution to this? The first thing that comes to mind is that it’s a login/permissions thing, but it’s really hard to tell what’s going on from afar. The only suggestion I have is to put copious print statements in your code to find out exactly where it’s failing.

      • ninabean says:

        I’m having the same problem. It’s just a basic “open text file and write to it” script. It runs fine from PythonWin. But from Task Scheduler it says it ran successfully but no text file gets created. If I run it using Python.exe as the program and the script as the argument, the Windows command prompt runs quickly and I see the word “error” but it goes so fast I can’t see what it says. Then if I run it just using the .py file as the program to run, all it does is open PythonWin.

  7. eversole says:

    What is the name of the Name of the example Model?

    • Dale Honeycutt says:

      The example model is named “ImportGPX”
      To call the model in arcpy, you need to supply the tool name (“ImportGPX”), and underscore, followed by the alias of the toolbox in which it resides (in this case “gpxtools”, a custom toolbox):
      Does this help?

  8. gbaxter says:

    Just a heads up, I tried executing the exact code and it wouldn’t work unless I include “import time” at the beginning of my script.

  9. chandrakanth_reddy says:

    Thanks.Very good Explanation but i have one doubt,. the scheduled script doesn’t execute when the computers enter in to sleep mode.Is there any way to make the script execute even when the computer enters in to sleep mode.

  10. daveatcogs says:

    A very useful post.
    I used it to figure out how to run a process updating a feature service with the position of the International Space Station. This map consumes the result (and the map updates every minute). The task re-starts every five minutes; the python code updates the ISS position once a minute for five minutes.
    The benefit of having this run as a scheduled task is: by having the task “re-start” every 5 minutes, any “python errors” or “network access errors” or “URL access errors” could “get fixed” for the next instance. When simply running the process in a long loop, I was constantly having to re-start due to one of these errors.
    Thank you Ghislain & Dale.

  11. brian.anderson_mcfcd says:

    Thanks for the post this works great if my computer is on. However, here is my problem. I’ve got a simple python script (100 lines or so) that takes an Excel 97-2003 table, creates a feature class, adds attributes, and then uses data driven pages to output PDF maps. The Excel table is generated daily (M-F, non-holidays) from a MS 2013 Access database. The script and the table are stored on network drives and the output PDF’s go to a network drive. My problem is in trying to automate. The Access data input and Excel table generation are done before I get to work and I’m not supposed to leave my computer on. I use an Advanced (ArcInfo) Concurrent Use License for ArcMap 10.2 Desktop. The script is on the same server as the Concurrent License. What I’m trying to do is find some way to run the script right after the Excel table is created without me having to have my computer turned on. I was thinking of copying my C:\Python27\ArcGIS10.2 data to the computers that run the MS Access database but that’s about 83.3 MB I would have to copy to any and all of the computers that would be used to generate the Excel table. Then I would have to set up the Windows Task Scheduler on each of the computers. This would mean the script would be run multiple times (once for each computer that is turned on). I’m not sure the IT Department would even let me do this. Also, while the mxd is stored on the same server as the script, the other computers don’t have ArcMap so would the script even work? I do have access to ArcServer 10.1 which is on the same server as the script but I don’t know if ArcServer can run a python script or how to set it up if it does. ANY suggestions would be greatly appreciated.

    • slradke_ousd says:

      Trying to run a model that has no parameters. I wrote a script to import a toolbox, and then run a model, as follows:

      import arcpy
      # Import the toolbox containing the model. Toolbox file name is GeoQueue.tbx. Alias is GeoToolBox
      arcpy.ImportToolbox(r”C:\Users\susan.radke\AppData\Roaming\ESRI\Desktop10.3\ArcToolbox\My Toolboxes\GeoQueue.tbx”)
      # Run the model.

      Not working. Getting the following error:
      File “C:\Python27\ArcGIS10.3\Lib\site-packages\pythonwin\pywin\framework\”, line 325, in RunScript
      exec codeObject in __main__.__dict__
      File “C:\Oakland_OUSD\SLR_OUSD_GIS\2015_16\GeoQueue\GeoQueueRun\GeoQueue_Python\”, line 5, in
      AttributeError: ‘module’ object has no attribute ‘GeoQueueGeocode_GeoToolBox’

      What am I missing?

    • pdavidson says:

      Interesting, most IT groups want your PC left on.
      So they can push updates.
      Because the biggest hit it takes is during current in rush on power up.
      I’d say get permissions to leave yours on, explain that it is running scripts over night.
      Or, find a server running where you can you run scripts. That’s the more common process.
      Running scripts on local PCs is usually a bad idea in terms of long term continuity.
      You leave, no one knows why the PDFs are no longer being generated…

      • mruiz says:


        I am having the same trouble but with the AcceptConnections. The error shown is:

        AttributeError: ‘module’ object has no attribute ‘AcceptConnections’

        I am running the script at the server side. I tried with the admin and with the sde and the error still appears….

        Any idea?

        Thanks in advance!

  12. mpat001 says:

    Thanks Dale and Ghislain. Really helpful.

  13. dizcinger says:

    Excellent post.- this has helped me a lot! I think you are missing a closing bracket right above the ‘Advanced options’ section, where the os.rename is.

  14. jarvis says:

    Very informative! Thanks for posting!

  15. maryandrews says:

    This is a bit off topic but I can’t find the answer anywhere so I’m desperate for help.
    I have a python script that generates a number of PDFs from different mxds. If I run the script from Pythonwin everything works great. When I run the script via task manager it leaves off layers that are turned on and available in the mxd such as street labels. Sometimes it even leaves out all but one layer. Has anyone had this issue? Any ideas?

  16. says:

    We wish to link an ESRI geodatabase to a ‘.mdb’ database. The ‘mdb’ database is updated daily. We would like to make sure that the GDB is up to date whenever updates are made to the ‘.mdb’. The database is created from ‘Acquire’, and is exported in ‘.mdb’ format.

  17. abeckmu19 says:

    Very helpful. Thanks!