SQL Server Agent Job Timeout

旧巷老猫 提交于 2019-11-29 01:34:26

We do something like the code below as part of a nightly job processing subsystem - it is more complicated than this actually in reality; for example we are processing multiple interdependent sets of jobs, and read in job names and timeout values from configuration tables - but this captures the idea:

    DECLARE @JobToRun NVARCHAR(128) = 'My Agent Job'
DECLARE @dtStart DATETIME = GETDATE(), @dtCurr DATETIME
DECLARE @ExecutionStatus INT, @LastRunOutcome INT, @MaxTimeExceeded BIT = 0
DECLARE @TimeoutMinutes INT = 180 

EXEC msdb.dbo.sp_start_job @JobToRun
SET @dtCurr = GETDATE()
WHILE 1=1
BEGIN
    WAITFOR DELAY '00:00:10'
    SELECT @ExecutionStatus=current_execution_status, @LastRunOutcome=last_run_outcome 
    FROM OPENQUERY(LocalServer, 'set fmtonly off; exec msdb.dbo.sp_help_job') where [name] = @JobToRun
    IF @ExecutionStatus <> 4
    BEGIN -- job is running or finishing (not idle)
        SET @dtCurr=GETDATE()
        IF DATEDIFF(mi, @dtStart, @dtCurr) > @TimeoutMinutes
        BEGIN   
            EXEC msdb.dbo.sp_stop_job @job_name=@JobToRun                   
            -- could log info, raise error, send email etc here
        END
        ELSE
        BEGIN
            CONTINUE
        END
    END
    IF @LastRunOutcome = 1  -- the job just finished with success flag
    BEGIN
        -- job succeeded, do whatever is needed here
        print 'job succeeded'                                   
    END

END

What kind of a job is this? You may want to consider putting the whole job in a TSQL script within a While loop. The condition to check would obviously be the time difference between current time and job start time.

Raj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!