Search code examples
sql-serverschedulerwindows-task-scheduler

SQL Server create a task with xp_cmdshell and set if the task failed restart every time


I know how to create a task in SQL Server 2008 by query, but I can not configure this "if the task fails, restart every time" and how to disable "stop the task if it runs longer than" .

This it is my code

declare @cmd varchar(max), @Path varchar(max), @FileToExecute varchar(max)

set @Path = 'C:\MyAppFolder'
set @FileToExecute = 'MyApp.exe'

set @cmd = 'schtasks /create /tn "DataTask" /tr "'''+@Path+'\'+@FileToExecute +'''" /sc onstart /RU Administrator /RP password /F /delay 0015:00'  

exec xp_cmdshell @cmd  , NO_OUTPUT

set @cmd = 'schtasks /run /TN "DataTask"'            
exec xp_cmdshell @cmd 

Example


Solution

  • I don't think can do it all from command line.. this is all you can do

    https://msdn.microsoft.com/en-us/library/windows/desktop/bb736357(v=vs.85).aspx

    but... you could have made an XML file by exporting and existing job:

    schtasks /create /xml "MyExportFile.xml" /tn "Name of the New Task"
    

    and adjust the settings like this:

    <Settings>
        <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
        <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
        <StartWhenAvailable>true</StartWhenAvailable>
        <RestartOnFailure>
          <Interval>PT30M</Interval>
          <Count>5</Count>
        </RestartOnFailure>
        <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    </Settings>
    

    And you can them use that as a template for importing from command line