Scheduled Job triggers a notification

aniellacerna
Tera Contributor

scheduled job that will trigger the notification daily but will not run if the current date is out of schedule (8-5 weekdays).

what script can i use in this situation

1 REPLY 1

Danish Bhairag2
Tera Sage
Tera Sage

Hi @aniellacerna ,

 

To achieve your requirement of triggering a scheduled job for notifications daily within a specific time range (8 AM to 5 PM) on weekdays (Monday to Friday), and not running the job if the current date is outside of this schedule, you can use a combination of scheduled job configuration and a script condition. Here's how you can set it up:

 

1. **Scheduled Job Configuration:**

   - Create a new scheduled job in ServiceNow.

   - Configure the job to run daily at a specific time, say 8 AM.

   - Set the "Repeat" option to "Daily."

   - Do not enable the "Repeat on Weekends" option to ensure it runs only on weekdays (Monday to Friday).

 

2. **Script Condition:**

   - Add a script condition within the scheduled job script to check the current time and day before executing the notification logic.

   - Use JavaScript's Date object to get the current day of the week (0 for Sunday, 6 for Saturday) and current time in hours (24-hour format).

   - Check if the current day is within Monday to Friday and the current time is between 8 AM and 5 PM.

   - If the condition is met, execute the notification logic. If not, the script should exit without performing any further actions.

 

Example Script for the Scheduled Job:

 

(function executeScheduledJob() {

    var now = new Date();
    var currentDay = now.getDay(); // 0 (Sunday) to 6 (Saturday)
    var currentHour = now.getHours(); // 0 to 23

    // Check if the current day is Monday to Friday and the current time is between 8 AM and 5 PM
    if (currentDay >= 1 && currentDay <= 5 && currentHour >= 8 && currentHour < 17) {
        // Execute your notification logic here
        gs.log("Notification logic executed at " + now);
        // Your notification code goes here
    } else {
        // Outside of schedule, do nothing
        gs.log("Job skipped due to out-of-schedule timing at " + now);
    }

})();

 

In this script, the `executeScheduledJob` function checks the current day and time. If the current day is between Monday to Friday (1 to 5) and the current time is between 8 AM and 5 PM (8 to 16 in 24-hour format), the notification logic will be executed. If the current time is outside of this range or it's a weekend, the script will log a message indicating that the job was skipped due to being out of schedule.

 

Thanks,

Danish