Select to view content in your preferred language

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

2442
12
04-03-2018 10:37 AM
ToniSlyer
Emerging 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
JakeSkinner
Esri Esteemed Contributor

Hi Toni,

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

0 Kudos
ToniSlyer
Emerging 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')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)
logger.info('--Script Began Running')
logger.info('--End MXD copy from fileshare to local data store.')

# Define local variables
wrkspc = 'D:/MXDs/Test/'
TestMap = arcpy.mapping.MapDocument(wrkspc + 'Test.mxd')
logger.info('-- 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'
logger.info('-- Server Connection Defined')

logger.info('-- Begin overwrite of Test service')
# Provide other service details
TestService = 'Test'
sddraft_Test = wrkspc + TestService + '.sddraft'
sd_Test = wrkspc + TestService + '.sd'

logger.info('-- 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 keyValue.firstChild.data == "WebCapabilities":
                keyValue.nextSibling.firstChild.data = "Query,Create,Update,Delete"

f = open(sddraft_Test, 'w')
doc.writexml( f )
f.close()

logger.info('-- 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
logger.info( 'The following information was returned during analysis of the MXD:')
for key in ('messages', 'warnings', 'errors'):
        logger.info( '----' + key.upper() + '---')
        vars = analysis[key]
        for ((key, code), layerlist) in vars.iteritems():
                logger.info( "'%s' code '%s'", key, code)
                logger.info( '       applies to: ',)
                for layer in layerlist:
                        logger.info( layer.name,)
                #logger.info()

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

       
else:
        logger.info('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 "logger.info('-- Create service definition draft of Test service')" is where the task fails in the scheduled task. 

0 Kudos
JakeSkinner
Esri Esteemed Contributor

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

https://community.esri.com/docs/DOC-8691-posting-code-with-syntax-highlighting-on-geonet 

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

0 Kudos
ToniSlyer
Emerging Contributor

Yes, I edited the above post. 

0 Kudos
JonathanQuinn
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
ToniSlyer
Emerging Contributor

When I run the task in the Windows Scheduler, it runs until line "logger.info('-- 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
BerendVeldkamp
Frequent Contributor

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

0 Kudos
ToniSlyer
Emerging 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
BerendVeldkamp
Frequent Contributor

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