How to determine if a SQL job is running

I received a (initially) strange request to determine whether a SQL job is currently running or not.

And researching it was useful, but it didn't quite tie all together for me.

So, I'm posting this T-SQL snippet (which can be wrapped up into a stored procedure, if you wish) that determines whether a SQL job is running. For this example, I've hard-coded the name of the SQL Job...

Enjoy!

 

SET NOCOUNT ON

DECLARE @isRunning BIT

DECLARE @xp_results TABLE (job_id                UNIQUEIDENTIFIER NOT NULL,

                            last_run_date         INT              NOT NULL,

                            last_run_time         INT              NOT NULL,

                            next_run_date         INT              NOT NULL,

                            next_run_time         INT              NOT NULL,

                            next_run_schedule_id  INT              NOT NULL,

                            requested_to_run      INT              NOT NULL, -- BOOL

                            request_source        INT              NOT NULL,

                            request_source_id     sysname          COLLATE database_default NULL,

                            running               INT              NOT NULL, -- BOOL

                            current_step          INT              NOT NULL,

                            current_retry_attempt INT              NOT NULL,

                            job_state             INT              NOT NULL)

 

BEGIN TRY

      SET @isRunning = 0;

     

      INSERT INTO @xp_results

      EXECUTE master.dbo.xp_sqlagent_enum_jobs 1, 'dbo'

 

      -- next line is for debugging purposes only

      -- SELECT * FROM @xp_results

     

      SELECT @isRunning = xpr.running                

      FROM @xp_results xpr

            INNER JOIN dbo.sysjobs_view sjv ON xpr.job_id = sjv.job_id

      WHERE sjv.name='SQLJobName'

END TRY

BEGIN CATCH

END CATCH

 

SELECT ISNULL(@isRunning,0) AS [IsRunning]

 

4 Comments

  • -- Microsoft SQL Server 2008 Standard Edition:
    IF EXISTS(SELECT 1 FROM msdb.dbo.sysjobs J JOIN msdb.dbo.sysjobactivity A ON A.job_id=J.job_id WHERE J.name=N'Your Job Name' AND A.run_requested_date IS NOT NULL AND A.stop_execution_date IS NULL)
    PRINT 'The job is running!'
    ELSE
    PRINT 'The job is not running.'

  • Thanks John!
    Your tip helped me a lot!

  • Just the ticket. Thanks.
    @Pavel - I don't think stop_execution_date can be relied upon to determine if the job is ruuning, especially if a job has not run at all in the current Agent session (i.e. need to use max(session_id)). Even then a null stop_execution_date does not mean the job is running.

  • That the difference between that the right word and that the just about right word is more than just a excellent line!

    it’s for example that the difference between a lightning bug and that the lightning!

Comments have been disabled for this content.