Send alert when SQL agent job runs longer than average run time history

mdhar 41 Reputation points
2020-11-13T10:26:47.407+00:00

I would like to know when a specific sql agent job is running longer than average run time history and then send a email alert with job name and duration. Any help is appreciated. Thanks.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,625 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. tibor_karaszi@hotmail.com 4,311 Reputation points
    2020-11-13T12:25:17.837+00:00

    Create a query which uses the job history tables in msdb and for your job extracts the average running time. Now schedule a job which uses this query to check the currently executing job and see if it has executed longer than the average job. If it has, then use sp_send_dbmail to send en email (if that is what you want).

    0 comments No comments

  2. Tom Phillips 17,731 Reputation points
    2020-11-13T17:59:43.173+00:00

    Be careful with the query of the history tables. There are circumstances where job can still show "running" even though it has errored or SQL Agent has been shutdown and restarted.

    0 comments No comments

  3. MelissaMa-MSFT 24,196 Reputation points
    2020-11-16T07:50:30.487+00:00

    HI @mdhar ,

    You could refer below query which could determines how long (in seconds) a specific sql agent job is currently running.

    SELECT DATEDIFF(SECOND,aj.start_execution_date,GetDate()) AS Seconds  
    FROM msdb..sysjobactivity aj  
    JOIN msdb..sysjobs sj on sj.job_id = aj.job_id  
    WHERE aj.stop_execution_date IS NULL -- job hasn't stopped running  
    AND aj.start_execution_date IS NOT NULL -- job is currently running  
    AND sj.name = 'JobX'--job name  
    and not exists( -- make sure this is the most recent run  
        select 1  
        from msdb..sysjobactivity new  
        where new.job_id = aj.job_id  
        and new.start_execution_date > aj.start_execution_date  
    )  
    

    You could also refer the code in below link and check whether it is helpful to you.
    HOW TO: Find Currently Running Long SQL Agent Jobs

    Then you could modify above code by adding sp_send_dbmail to send an email with job name and duration.

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Hot issues November--What can I do if my transaction log is full?--- Hot issues November
    Hot issues November--How to convert Profiler trace into a SQL Server table -- Hot issues November

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.