Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Agent Job Timeout

I have just had a scheduled SQL Server job run for longer than normal, and I could really have done with having set a timeout to stop it after a certain length of time.

I might be being a bit blind on this, but I can't seem to find a way of setting a timeout for a job. Does anyone know the way to do it?

Thanks

like image 297
Iain Hoult Avatar asked Oct 19 '09 13:10

Iain Hoult


People also ask

How do I increase SQL job timeout?

Connect to MS SQL server via SQL Management Studio. In Object Explorer, right-click on the server name and then select Properties. In the new tab, click on Connections node. In Remote Query Timeout change it to your desired value or specify 0 to set no limit.

Why does SQL Server Agent stop automatically?

SQL Server is terminating because of fatal exception c0000005. This error may be caused by an unhandled Win32 or C++ exception, or by an access violation encountered during exception handling. Check the SQL error log for any related stack dumps or messages. This exception forces SQL Server to shutdown.


1 Answers

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
like image 149
PaulR Avatar answered Sep 18 '22 15:09

PaulR