logo

NJP

Better Conditions for Scheduled Jobs (Specific times or days of week)

Import · Apr 30, 2021 · article

We've run into a number of cases where we would like scheduled jobs to run at specific times of day on specific days of the week. This condition script will make it very simple to define which times of day and/or days of week you want your scheduled job to run.

To use this script:

  1. Set the schedule job to RUN: Periodically
  2. Set the REPEAT INTERVAL to 0 Days, 1 Hours (this causes the script to check whether it should run once every hour)
  3. Check the CONDITIONAL box
  4. Copy and paste the entire script below into the CONDITION script
  5. Update the "runHours" and "runWeekdays" variables in the script as follows:

runHours: Which hour(s) of the day should the job run? Can be one or multiple values. Examples:runHours = [9] //Only send at 9 amrunHours = [0, 13] //Run at midnight and 1 pm

runHours = [8, 12, 17] //Run at 8 am, 12 pm, 5 pm

runWeekdays: Which days of the week should the job run? Can be one or multiple values. (Monday = 1, Tuesday = 2... Sunday = 7)Examples: runWeekdays = [1, 2, 3, 4, 5] //Run on weekdays - Mon through FrirunWeekdays = [1, 3, 5] //Run Mon, Wed, Fri

runWeekdays = [6, 7] //Run Sat & Sun

//Use Run: Periodically, Interval: 1 hour (check conditions every hour - send if appropriate)
(function () {

    var runHours = [9, 14, 16]; //Hour of day to send (24 hour time)
    var runWeekdays = [1, 2, 3, 4, 5]; //Days of week - (Mon = 1, Tues = 2... Sun = 7)
    var answer = false; //Default to false

    var shouldRunToday = checkRunWeekday(runWeekdays);
    var shouldRunThisHour = checkRunHour(runHours);

    if (shouldRunToday && shouldRunThisHour) answer = true;

    return answer;

})();

function checkRunWeekday(runDays) {
    //Return true if we should send today. Otherwise, return false
    var currentDayOfWeek = getCurrentDayOfWeek();
    if (runDays.indexOf(currentDayOfWeek) > -1) return true;
    return false;
}

function getCurrentDayOfWeek() {
    var gdt = new GlideDateTime();
    var dayOfWeek = gdt.getDayOfWeekLocalTime();
    return dayOfWeek;
}

function checkRunHour(runHours) {
    //Return true if we should send this hour. Otherwise, return false
    var hour = getCurrentHour();
    if (runHours.indexOf(hour) > -1) return true;
    return false;
}

function getCurrentHour() {
    var gt = new GlideTime();
    var hour = gt.getHourOfDayLocalTime();
    return hour;
}

Note that this uses "local" time. Make sure you test and adjust as appropriate. I believe time zone is decided based on the "Run As" user of the scheduled job.

Author note: I've written the script to be easy to read/parse. It could easily be consolidated down to a few lines of code, but I prefer to write "self documenting code" where possible.

Labels:

image

View original source

https://www.servicenow.com/community/now-platform-articles/better-conditions-for-scheduled-jobs-specific-times-or-days-of/ta-p/2323594