sql-server – SQL Server代理作业超时

前端之家收集整理的这篇文章主要介绍了sql-server – SQL Server代理作业超时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚有一个计划的sql Server作业运行时间超过正常,我真的可以设置一个超时,以在一段时间后停止.

我可能对此有点盲目,但我似乎找不到设置工作超时的方法.有人知道这样做吗?

谢谢

解决方法

作为夜间工作处理子系统的一部分,我们像下面的代码一样做,这比实际上更复杂;例如,我们正在处理多个相互依赖的作业集合,并从配置表中读取作业名称和超时值 – 但是它捕获了这个想法:
  1. DECLARE @JobToRun NVARCHAR(128) = 'My Agent Job'
  2. DECLARE @dtStart DATETIME = GETDATE(),@dtCurr DATETIME
  3. DECLARE @ExecutionStatus INT,@LastRunOutcome INT,@MaxTimeExceeded BIT = 0
  4. DECLARE @TimeoutMinutes INT = 180
  5.  
  6. EXEC msdb.dbo.sp_start_job @JobToRun
  7. SET @dtCurr = GETDATE()
  8. WHILE 1=1
  9. BEGIN
  10. WAITFOR DELAY '00:00:10'
  11. SELECT @ExecutionStatus=current_execution_status,@LastRunOutcome=last_run_outcome
  12. FROM OPENQUERY(LocalServer,'set fmtonly off; exec msdb.dbo.sp_help_job') where [name] = @JobToRun
  13. IF @ExecutionStatus <> 4
  14. BEGIN -- job is running or finishing (not idle)
  15. SET @dtCurr=GETDATE()
  16. IF DATEDIFF(mi,@dtStart,@dtCurr) > @TimeoutMinutes
  17. BEGIN
  18. EXEC msdb.dbo.sp_stop_job @job_name=@JobToRun
  19. -- could log info,raise error,send email etc here
  20. END
  21. ELSE
  22. BEGIN
  23. CONTINUE
  24. END
  25. END
  26. IF @LastRunOutcome = 1 -- the job just finished with success flag
  27. BEGIN
  28. -- job succeeded,do whatever is needed here
  29. print 'job succeeded'
  30. END
  31.  
  32. END

猜你在找的MsSQL相关文章