How to publish a Map service using the Windows Task Scheduler?

04-03-2018 10:37 AM
New Contributor

I am currently trying to automate the steps of publishing a map service and create scheduler tasks to allow the maps to publish automatically. Currently my code creates and save the new mxd, Creates a service definition draft of the service, analyzes the draft for errors and if there are no errors the service is published to the arcgis server manager. The script works as expected running the script as a .bat file. However in the Windows Task scheduler the script fails at the line that creates the service definition draft. 

The task is already set to "Run with Highest privileges" and "Run whether user is logged on or not"

Does anyone know how to make the script run in the task scheduler?

0 Kudos
12 Replies
Esri Esteemed Contributor

Hi Toni,

Can you post your script here?  It will help with the trouble shooting. 

0 Kudos
New Contributor
# Publishes a service to machine myserver using Test.mxd
# A connection to ArcGIS Server must be established in the
#  Catalog window of ArcMap before running this script
import arcpy, sys, os, logging, subprocess, shutil, glob, urllib2, urllib, ssl
from time import strftime
import xml.dom.minidom as DOM

logger = logging.getLogger('myapp')
hdlr = logging.FileHandler(strftime('D:\\Temp\\logs\\Test_OverWrite_%H%M%S_%m_%d_%Y.log'))
hdlr.suffix = '%H_%M_%d_%m_%Y.log.log'
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
logger.setLevel(logging.INFO)'--Script Began Running')'--End MXD copy from fileshare to local data store.')

# Define local variables
wrkspc = 'D:/MXDs/Test/'
TestMap = arcpy.mapping.MapDocument(wrkspc + 'Test.mxd')'-- Local varbles Defined')

# Provide path to connection file
# To create this file, right-click a folder in the Catalog window and
# click New > ArcGIS Server Connection
con = 'D:\Temp\ArcGIS Connection\ArcGISAdminConnection.ags''-- Server Connection Defined')'-- Begin overwrite of Test service')
# Provide other service details
TestService = 'Test'
sddraft_Test = wrkspc + TestService + '.sddraft'
sd_Test = wrkspc + TestService + '.sd''-- Create service definition draft of Test service')
# Create service definition draft
arcpy.mapping.CreateMapSDDraft(TestMap, sddraft_Test, TestService, 'ARCGIS_SERVER', con, True, None)
doc = DOM.parse(sddraft_Test)

configProps = doc.getElementsByTagName('Info')[0]
propArray = configProps.firstChild
propSets = propArray.childNodes
for propSet in propSets:
    keyValues = propSet.childNodes
    for keyValue in keyValues:
        if keyValue.tagName == 'Key':
            if == "WebCapabilities":
       = "Query,Create,Update,Delete"

f = open(sddraft_Test, 'w')
doc.writexml( f )
f.close()'-- Analyze the service definition draft')
# Analyze the service definition draft
analysis = arcpy.mapping.AnalyzeForSD(sddraft_Test)

# Print errors, warnings, and messages returned from the analysis 'The following information was returned during analysis of the MXD:')
for key in ('messages', 'warnings', 'errors'): '----' + key.upper() + '---')
        vars = analysis[key]
        for ((key, code), layerlist) in vars.iteritems():
       "'%s' code '%s'", key, code)
       '       applies to: ',)
                for layer in layerlist:

# Stage and upload the service if the sddraft analysis did not contain errors
if analysis['errors'] == {}:'-- No errors occured, Service is being published')
        # Execute StageService. This creates the service definition.
        arcpy.StageService_server(sddraft_Test, sd_Test)

else:'Service could not be published because errors were found during analysis.')
        print "Service could not be published because errors were found during analysis."
print arcpy.GetMessages()‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Above a snippet of my script, the next lines of code start the service on the server.  Where the script says "'-- Create service definition draft of Test service')" is where the task fails in the scheduled task. 

0 Kudos
Esri Esteemed Contributor

Can you re-post the code following the steps in the below link? 

It will format the syntax correctly and make it easier to read.

0 Kudos
New Contributor

Yes, I edited the above post. 

0 Kudos
Esri Notable Contributor

What error do you get? You may want to wrap it in a try: except block and write the error to disk.

0 Kudos
New Contributor

When I run the task in the Windows Scheduler, it runs until line "'-- Create service definition draft of Test service')" . But never gets past that point, and the task attempts to keep running but never completes till I manually stop it. There is no error in the scheduler I am giving "The task is currently running.(0x41301)" line , even though the script is not progressing. 

0 Kudos
Occasional Contributor II

Which user account is set to run the scheduled task? Does it have the necessary privileges?

0 Kudos
New Contributor

I have tried running the script on a few different user accounts such as system, my administrator account and my user account. The only account that works is my personal user account but under that account I can not select "Run whether user is logged on or not", which is needed for my scheduled updates. 

0 Kudos
Occasional Contributor II

The script probably needs to access the network, so I'd try the system account 'NETWORK' first.

Obviously, the account needs to be able to access the .mxd and the .ags connection file as well, so you might want to check that (use procmon: Process Monitor - Windows Sysinternals | Microsoft Docs) .

Another thing to check would be proxy settings, if you have one. Those might be configured for your personal account, but not for others.

0 Kudos