動態

詳情 返回 返回

sqlserver系統表查出job的下一次運行時間異常現象 - 動態 詳情

前兩天某SQLServer服務器斷斷續續出現性能問題,綜合排查之後懷疑是job定時任務引起的,於是查了一下job的schedule和最近一次執行情況。
大部分job的schedule都沒有問題,由於當前實例是啓用了複製分發,無意中喵到'Distribution clean up: distribution這個job的下一次執行時間明顯不正常,下一次運行時間跟上一次運行時間一樣???
啓用了複製分發之後,自動生成的Distribution clean up: distribution這個job還是比較熟悉的,該job是每10分鐘運行一次,這裏查出來的LastRunDateTime和NextRunDate竟然是一樣的?
一度懷疑這個SQL有問題,不過也用了很多年了,之前也沒有留意有這個細節問題。

image

但是通過作業活動監視器(job activity monitor)看到job的下一次運行時間又是正常的。

image

查了下資料,有人指出這種方式查詢出來的下一次運行時間有同樣的問題,原來這是一個一直存在的問題,評論區裏出高手:
The only problem with this query is that the next_run_time value could be not accurate for jobs with an interval less then 20min because the sysjobschedules view is refreshed at the same interval, 20min. So the view (and the query from the article) will return a next_run_time that is actually in the past until the next time it will be refreshed. 
就是説SQLServer系統表刷新間隔是20mins一次,如果一個job執行完之後,還沒有來得及刷新,查出來的最後執行時間以及下一次執行時間可能是不準確的,可以通過exec msdb.dbo.sp_get_composite_job_info這個系統存儲過程來查詢。

https://blog.sqlauthority.com/2008/12/22/sql-server-find-next-running-time-of-scheduled-job-using-t-sql/ 參考評論區
image

image

T-SQL代碼

select 
	 j.name as 'JobName'
	 ,j.job_id
	 ,case h.run_status
		when 0 then 'Failed'
		when 1 then 'Succeeded'
		when 2 then 'Retry'
		when 3 then 'Canceled'
		when 4 then 'In Progress'
	else 'unknow' end as RunStatus
	 ,msdb.dbo.agent_datetime(run_date, run_time) as 'LastRunDateTime'
	 ,run_duration as [RunDuration]
	 ,sj.next_run_date
	 ,sj.next_run_time
	 ,case 
		 when sj.next_run_date>0 and sj.next_run_time>0 
			then  msdb.dbo.agent_datetime(sj.next_run_date, sj.next_run_time)
		 else 
			null  end as 'NextRunDateTime'
From msdb.dbo.sysjobs j 
cross apply 
(
	--這個order by instance_id desc,是job最後一次運行,並且是最後一步,instance_id最大值其step_id=0,整個job所有步驟執行時間的彙總
	--步驟 ID:step_id=0:整個 Job 的彙總記錄(開始和結束信息);step_id>0:Job 的具體步驟號。
	select top 1 * from msdb.dbo.sysjobhistory h 
	where j.job_id = h.job_id order by instance_id desc 
)h
left join msdb.dbo.sysjobschedules sj on j.job_id = sj.job_id  
where  j.name  = 'Distribution clean up: distribution'
order by JobName desc

--懷疑上面SQL有問題,單獨查原始表,結果也是一樣的
select * from msdb.dbo.sysjobs where job_id = 'BECFCA04-E800-4F8B-9FCA-F3DFDD279C11';
select * from msdb.dbo.sysjobschedules where job_id = 'BECFCA04-E800-4F8B-9FCA-F3DFDD279C11';



--啓用OPENROWSET
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;

EXEC sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;

--通過OPENROWSET執行,可以篩選出想要的字段
SELECT *
FROM OPENROWSET('SQLNCLI', 'server=localhost,2433;UID=sa;PWD=******;','exec msdb.dbo.sp_get_composite_job_info')

--或者執行執行sp_get_composite_job_info
exec msdb.dbo.sp_get_composite_job_info

 

Add a new 評論

Some HTML is okay.