ServiceNow Certification Mock Exams
Click To View Now
SNOWYCODE
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
How To Exclude Weekends From Scheduled Jobs In ServiceNow
How To's

How To Exclude Weekends From Scheduled Jobs In ServiceNow

How To Exclude Weekends From Scheduled Jobs in ServiceNow

Use Cases

There's a lot of reasons that you may need a script that excludes (or includes) weekends when developing for a client in ServiceNow. A couple examples are:

  • You have a scheduled job that triggers an email notification, but you don't want it to send on weekends
  • You want all incidents that are created on the weekend to be set to a priority of High

Use the code templates and examples below to fit your requirement. You can update the IF statement to whatever you need (i.e. exclude weekdays, only run on Tuesdays and Thursdays, etc.).

The code:


 var d = new Date();
var day = d.getDay();

if ( day > 0 && day < 6 ) {
	answer =  true;
} else {
	answer =  false;
}

The code, with comments explaining it:

 // get the date in 'Thu Dec 08 2022 07:00:53 GMT-0800 (PST)' format
var d = new Date();
// convert the date to a number between 0-6 (0 is Sunday, 6 is Saturday)
var day = d.getDay();

// if the day is between 1 and 5 (Monday - Friday), then return true 
if ( day > 0 && day < 6 ) {
	answer = true;
} else {
	answer =  false;
}

Example - Scheduled Job:

In this example, we add this script to the 'Condition' field of a Scheduled Job. This will ensure that the job does *not* run on weekends.

Note: Wrapping the script in the function is not necessary, but is good practice.

 ( function () {

	var d = new Date();
	var day = d.getDay();
	
	if ( day > 0 && day < 6 ) {
		answer = true;
	}

	answer = false;

} ) ();

Here's what your Scheduled Job should look like:

Scheduled Job Only Run On Weekdays

Example - Business Rule:

In this example, we write a Business Rule script (before insert), that sets the Urgency field to '1 - High' if the Incident was created on the weekend.

 (function executeRule(current, previous /*null when async*/) {

	var d = new Date();
	var day = d.getDay();

	if ( day > 0 && day < 6 ) {
		current.urgency = 1;
	}

})(current, previous);

Summary

This script can be modified however you need it to be. Keep in mind that each day of the week is assigned a number, so you can set the IF statement to include or exclude whichever days you need! For quick reference, the number assigned to each day is:

Sunday - 0

Monday - 1

Tuesday - 2

Wednesday - 3

Thursday - 4

Friday - 5

Saturday - 6

And that's it! If you need any additional scripting templates, check out our Cheat Sheets.

Looking for something else? Check out our other posts below!

Snowycode team
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Read more