Alert Procedure for Long-Running Job
For jobs that run periodically and should take only a short time to run, a DBA may want to know when the job has been running for an excessive time. In this case, just checking to see IF the job is running won't do; the ability to make sure that it hasn't been running for a long period is needed. Matching the job id to a process id in sysprocesses requires some re-arranging of the job id to do the match. This script creates a stored procedure that will accept a job name, maximum run time allowed, and email address to notify. It will then use the job name to re-string the job number and check sysprocesses (based on the process id being part of the program name) to determine the amount of time the job has been runing, then alert if that time is over the "time allowed" parameter.
CREATE proc sp_check_job_running
DECLARE @var1 char(1),
select @job_id_char = substring(CAST(job_id AS char(50)),1,8)
where name = @job_name
select @process_id = substring(@job_id_char,7,2) +
select @minutes_running = DATEDIFF(minute,last_batch, getdate())
where program_name LIKE ('%0x' + @process_id +'%')
if @minutes_running > @minutes_allowed
select @message_text = ('Job '
+ ' has been running for '
+ SUBSTRING(CAST(@minutes_running AS char(5)),1,LEN(CAST(@minutes_running AS char(5))))
+ ' minutes, which is over the allowed run time of '
+ SUBSTRING(CAST(@minutes_allowed AS char(5)),1,LEN(CAST(@minutes_allowed AS char(5))))
+ ' minutes.')
@recipients = @person_to_notify,
@message = @message_text,
@subject = 'Long-Running Job to Check'
-- Typical job step syntax for job to do the checking