How to automatically STOP SQL Server Agent when no jobs are running?

前端 未结 4 1062
心在旅途
心在旅途 2021-01-23 12:23

I have around 40 different sql server jobs in one instance. They all have different schedules. Some run once a day some every two mins some every five mins. If I have a need to

4条回答
  •  自闭症患者
    2021-01-23 13:01

    how can I find the best time when no jobs are running so I won't interrupt any of my jobs?

    You basically want to find a good window to perform some maintenance. @MaxVernon has blogged about it here with a handy script

    /*
          Shows gaps between agent jobs
    -- http://www.sqlserver.science/tools/gaps-between-sql-server-agent-jobs/
    -- requires SQL Server 2012+ since it uses the LAG aggregate.
     Note: On SQL Server 2005, SQL Server 2008, and SQL Server 2008 R2, you could replace the LastEndDateTime column definition with:
    
           LastEndDateTime = (SELECT TOP(1) s1a.EndDateTime FROM s1 s1a WHERE s1a.rn = s1.rn - 1)
    */
    DECLARE @EarliestStartDate DATETIME;
    DECLARE @LatestStopDate DATETIME;
    SET @EarliestStartDate = DATEADD(DAY, -1, GETDATE());
    SET @LatestStopDate = GETDATE();
    ;WITH s AS 
    (
        SELECT StartDateTime = msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time)
              , MaxDuration = MAX(sjh.run_duration)
        FROM msdb.dbo.sysjobs sj 
              INNER JOIN msdb.dbo.sysjobhistory sjh ON sj.job_id = sjh.job_id
        WHERE sjh.step_id = 0
            AND msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time) >= @EarliestStartDate
            AND msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time) < = @LatestStopDate
        GROUP BY msdb.dbo.agent_datetime(sjh.run_date, sjh.run_time)
        UNION ALL
        SELECT StartDate = DATEADD(SECOND, -1, @EarliestStartDate)
            , MaxDuration = 1
        UNION ALL 
        SELECT StartDate = @LatestStopDate
            , MaxDuration = 1
    )
    , s1 AS 
    (
    SELECT s.StartDateTime
        , EndDateTime = DATEADD(SECOND, s.MaxDuration - ((s.MaxDuration / 100) * 100)
            + (((s.MaxDuration - ((s.MaxDuration / 10000) * 10000)) 
                        - (s.MaxDuration - ((s.MaxDuration / 100) * 100))) / 100) * 60
            + (((s.MaxDuration - ((s.MaxDuration / 1000000) * 1000000)) 
                        - (s.MaxDuration - ((s.MaxDuration / 10000) * 10000))) / 10000) * 3600, s.StartDateTime)
    FROM s
    )
    , s2 AS
    (
        SELECT s1.StartDateTime
            , s1.EndDateTime
            , LastEndDateTime = LAG(s1.EndDateTime) OVER (ORDER BY s1.StartDateTime)
        FROM s1 
    )
    SELECT GapStart = CONVERT(DATETIME2(0), s2.LastEndDateTime)
        , GapEnd = CONVERT(DATETIME2(0), s2.StartDateTime)
        , GapLength = CONVERT(TIME(0), DATEADD(SECOND, DATEDIFF(SECOND, s2.LastEndDateTime, s2.StartDateTime), 0))
    FROM s2 
    WHERE s2.StartDateTime > s2.LastEndDateTime
        ORDER BY s2.StartDateTime;
    

提交回复
热议问题