hourglass

A lot of people don’t know that there is an easy way to call a script to run asynchronously (with the next available worker thread) within the current ServiceNow API set.

There are a couple of Script Includes in the product that allow you to do this. The easiest API is the “ScheduleOnce” class. This class inherits from the “Schedule” class. The schedule class lets you set the schedule for a script while the ScheduleOnce class tells the system to throw it on the job queue and execute it at the next available spot.

To leverage the ScheduleOnce class, simply instantiate it, set the “script” variable with your script, and then call the “schedule()” method.

1
2
3
var so = new ScheduleOnce();
so.script = "//Your script as a string goes here";
so.schedule();

Please keep in mind that you cannot pass objects into the asynchronous script. You must represent everything as a string when you set the script variable.

Example

SchedOnceBR

For example, let’s say we have a Script Include library called “AuditWebService”. This library sends a web service call to a third party auditing server. This server wants to be notified any time the priority changes on any incident in the system. Not only does it want the current value, but the previous value as well.

We don’t want this to hold up the user experience, so we want to make this an asynchronous event. However, we can’t use the “async” business rule setting because we need both the current and previous versions of the priority. “async” business rules can only have the “current” values, and even that is limited on some fields based on the timing.

In order to do this, we will leverage the ScheduleOnce class within a “Before” business rule. The “Before” business rule still gives us the current and previous values from the business rule instance. But the ScheduleOnce allows us to tell the system to send the data asynchronously rather than hold up the save action for the web service call to go out.

Your business rule might look like this:

Name: Log Priority Change to Audit Server
Table: Incident [incident]
When: before
Insert: checked
Update: checked
Condition: current.priority.changes()
Script:

1
2
3
4
5
6
7
8
9
10
11
12
//Instantiate the ScheduleOnce class object
var so = new ScheduleOnce();

//Set the script variable to run the Audit Script Include
so.script = "var audit = new AuditWebService();";
so.script += "audit.setRecord('"+current.number+"');";
so.script += "audit.setPreviousPriority('"+previous.priority+"');";
so.script += "audit.setNewPriority('"+current.priority+"');"
so.script += "audit.sendToWebService();";

//Schedule the script to run
so.schedule();