Fixing Schedule-Based Date Calculation Issue in ServiceNow
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
2 hours ago
Overview
In recent times, I came across a requirement to automatically populate a date field (custom field – RCA due date) on Problem records during creation.
This article explains the issue encountered initially and the improved solution.
Requirement:
Auto-populate a date field on Problem record creation, calculate based on a defined business schedule (e.g., 8 AM to 5 PM), and add 5 working days (excluding non-working time).
Initial Approach:
An After Business Rule was created with the following logic:
- Loop through each day
- Check if the day falls within the schedule
- Continue until the required number of working days is reached
(function executeRule(current, previous /*null when async*/ ) {
if (current.due_date.nil()) {
var schedule = new GlideSchedule();
schedule.load('090eecae0a0a0b260077e1dfa71da828');
var gdt = new GlideDateTime();
var workingDaysToAdd = 5;
var workingDaysAdded = 0;
while (workingDaysAdded < workingDaysToAdd) {
gdt.addDaysLocalTime(1);
if (schedule.isInSchedule(gdt)) {
workingDaysAdded++;
}
}
current.due_date = gdt;
current.update();
}
})(current, previous);Issues Observed When record created after Schedule Hours:
- Problem records were delayed during creation
- Problem module hanging
- Some transactions took longer or failed
Why This Caused Issues:
When a record was created outside the defined schedule hours, the condition to increment workingDaysAdded was not met. As a result, the loop continued indefinitely, leading to an infinite loop, which caused delays and performance issues.
Optimized Solution:
The solution was redesigned to remove loops and use a more efficient approach.
Key Improvements
- Convert working days into total working hours
- Use
GlideSchedule.add()for direct calculation - Avoid loops and recursive updates
Updated Script
(function executeRule(current, previous /*null when insert*/) {
var startTime;
if (current.sys_created_on) {
startTime = new GlideDateTime(current.sys_created_on);
} else {
startTime = new GlideDateTime();
}
var hours = 45;
var dur = new GlideDuration(60 * 60 * 1000 * hours);
var schedule = new GlideSchedule('090eecae0a0a0b260077e1dfa71da828');
var end = schedule.add(startTime, dur);
current.due_date = end;
//current.update();
})(current, previous);
The above Business rule is more efficient with no impact on record creation performance, Cleaner and more maintainable code
I hope this article helps when working on similar schedule-based date calculation scenarios in ServiceNow.
Please mark this as helpful if you found it useful.
- Labels:
-
Problem Management
