What are Scheduled Jobs?

Scheduled Jobs execute scripts automatically at specified times or intervals. They automate routine tasks like data cleanup, report generation, and maintenance.

Background Execution

Scheduled Jobs run in the background without user interaction. They're perfect for maintenance, batch processing, and scheduled operations.

Creating Scheduled Jobs

Basic Scheduled Job Script
// Scheduled Job: Close Old Incidents
// Run: Daily at 2:00 AM
// Repeat: Daily

(function() {
    var gr = new GlideRecord('incident');
    gr.addQuery('state', '6'); // Resolved
    gr.addQuery('resolved_at', '<', gs.daysAgoStart(30));
    gr.query();
    
    var count = 0;
    while (gr.next()) {
        gr.state = '7'; // Closed
        gr.close_code = 'Solved (Permanently)';
        gr.close_notes = 'Auto-closed after 30 days';
        gr.update();
        count++;
    }
    
    gs.info('Auto-closed ' + count + ' old incidents');
})();
Scheduled Job: Generate Report
// Scheduled Job: Weekly Incident Report
// Run: Every Monday at 8:00 AM

(function() {
    // Get incidents from last week
    var ga = new GlideAggregate('incident');
    ga.addQuery('sys_created_on', '>=', gs.daysAgoStart(7));
    ga.groupBy('priority');
    ga.addAggregate('COUNT');
    ga.query();
    
    var report = 'Weekly Incident Report\n\n';
    while (ga.next()) {
        var priority = ga.priority.getDisplayValue();
        var count = ga.getAggregate('COUNT');
        report += priority + ': ' + count + ' incidents\n';
    }
    
    // Send email
    var email = new GlideEmailOutbound();
    email.setSubject('Weekly Incident Report');
    email.setBody(report);
    email.addAddress('manager@company.com');
    email.send();
    
    gs.info('Weekly report sent');
})();

Schedule Types

Schedule Type When It Runs Example
Run once One time only Import data on specific date
Daily Every day at specific time Nightly cleanup at 2 AM
Weekly Specific day(s) of week Monday morning reports
Monthly Specific day of month First of month billing
Periodically Every N minutes/hours Every 15 minutes integration

Events and Event Processing

Events trigger automated actions like notifications, scripts, and workflows. They provide loose coupling between system components.

Triggering Events
// Business Rule: Fire event when priority escalates
if (current.priority.changesFrom('3').changesTo('1')) {
    gs.eventQueue('incident.priority.critical', current, 
                  current.assigned_to, current.assignment_group);
}

// Script: Trigger custom event
gs.eventQueue('custom.order.shipped', orderRecord, 
              customer_sys_id, order_number);

// Fire event immediately (synchronous)
gs.eventQueueScheduled('incident.assigned', current, 
                       gs.nowDateTime(), current.assigned_to);
Script Action for Event
// Script Action: incident.priority.critical
// Runs when event fires

(function(current, event) {
    // Create high-priority task
    var task = new GlideRecord('incident_task');
    task.initialize();
    task.parent = current.sys_id;
    task.short_description = 'Urgent: Review critical incident ' + current.number;
    task.priority = '1';
    task.assigned_to = event.parm2; // From eventQueue parameter
    task.insert();
    
    // Log event
    gs.info('Critical incident task created: ' + current.number);
    
})(current, event);

Scheduled Job Best Practices

  • Schedule wisely: Run during off-peak hours to minimize impact
  • Use conditionals: Check conditions before processing (business hours, holidays)
  • Limit scope: Use setLimit() to process records in batches
  • Log activity: Use gs.info() to track execution
  • Error handling: Wrap in try-catch to prevent job failure
  • Test thoroughly: Test with "Execute Now" before scheduling
Robust Scheduled Job Template
(function() {
    try {
        var startTime = new GlideDateTime();
        gs.info('Starting scheduled job: MyJobName');
        
        // Main logic
        var gr = new GlideRecord('incident');
        gr.addQuery('active', true);
        gr.addQuery('priority', '1');
        gr.setLimit(100); // Process in batches
        gr.query();
        
        var processed = 0;
        while (gr.next()) {
            try {
                // Process each record
                gr.state = '2';
                gr.update();
                processed++;
            } catch (ex) {
                gs.error('Error processing record ' + gr.number + ': ' + ex.message);
            }
        }
        
        var endTime = new GlideDateTime();
        var duration = GlideDateTime.subtract(startTime, endTime);
        gs.info('Completed: Processed ' + processed + ' records in ' + 
                duration.getDisplayValue());
        
    } catch (ex) {
        gs.error('Scheduled job failed: ' + ex.message);
    }
})();

CSA & CAD Exam Questions (11 Questions)

What are Scheduled Jobs used for? Q1
CSA
  • A) Running scripts at specified times automatically
  • B) User interface customization
  • C) Form validation
  • D) Client-side automation
Show Answer
Correct Answer: A
Scheduled Jobs execute scripts automatically at specified times or intervals for maintenance, reporting, and batch processing.
Where do Scheduled Jobs execute? Q2
CSA
  • A) In the user's browser
  • B) On the server in the background
  • C) In the database
  • D) On the client device
Show Answer
Correct Answer: B
Scheduled Jobs execute on the server in the background, independent of user interaction.
How do you trigger an event in ServiceNow? Q3
CAD
  • A) gs.fireEvent()
  • B) gs.eventQueue()
  • C) gs.triggerEvent()
  • D) gs.createEvent()
Show Answer
Correct Answer: B
Use gs.eventQueue('event.name', record, parm1, parm2) to trigger events. Events are processed asynchronously.
Can Scheduled Jobs use GlideRecord? Q4
CSA
  • A) No, only GlideAggregate
  • B) Yes, they're server-side scripts
  • C) Only for reading data
  • D) Only with special permissions
Show Answer
Correct Answer: B
Yes! Scheduled Jobs are server-side scripts with full access to GlideRecord, gs, and all server APIs.
What happens when a Scheduled Job fails? Q5
CAD
  • A) It stops all scheduled jobs
  • B) Error is logged and job continues on schedule
  • C) System restarts
  • D) User receives notification
Show Answer
Correct Answer: B
When a Scheduled Job fails, the error is logged in the system log and the job continues on its normal schedule. Use try-catch for error handling.
What is a Script Action in event processing? Q6
CAD
  • A) Client-side script
  • B) Script that executes when an event fires
  • C) UI Action
  • D) Business Rule
Show Answer
Correct Answer: B
Script Actions are server-side scripts that execute when specific events are triggered, allowing event-driven automation.
How do you test a Scheduled Job before scheduling it? Q7
CSA
  • A) Schedule it for 1 minute from now
  • B) Use the "Execute Now" button
  • C) Cannot test, must schedule
  • D) Run in Scripts - Background
Show Answer
Correct Answer: B
Use "Execute Now" to test the Scheduled Job immediately before setting up the schedule. You can also test the script in Scripts - Background.
When should you use Scheduled Jobs? Q8
CAD
  • A) For real-time user interactions
  • B) For batch processing and maintenance tasks
  • C) For form validation
  • D) For client-side operations
Show Answer
Correct Answer: B
Use Scheduled Jobs for batch processing, data cleanup, report generation, and maintenance tasks that should run automatically at specific times.
Are events processed synchronously or asynchronously? Q9
CAD
  • A) Always synchronously
  • B) Always asynchronously
  • C) Depends on configuration
  • D) Random
Show Answer
Correct Answer: B
Events are processed asynchronously by default. Use gs.eventQueueScheduled() for scheduled event processing.
Can you pass parameters when firing an event? Q10
CAD
  • A) No, events have no parameters
  • B) Yes, via parm1 and parm2 in gs.eventQueue()
  • C) Only the record object
  • D) Maximum of one parameter
Show Answer
Correct Answer: B
Yes, pass parameters using: gs.eventQueue('event.name', record, parm1, parm2). Access in Script Action via event.parm1 and event.parm2.
What's the best practice for processing large datasets in Scheduled Jobs? Q11
CAD
  • A) Process all records at once
  • B) Use setLimit() to process in batches
  • C) Never process large datasets
  • D) Use client scripts instead
Show Answer
Correct Answer: B
Use setLimit() to process records in batches (e.g., 100 at a time) to avoid timeouts and performance issues. Schedule the job to run frequently to process all records over time.

Quick Reference

  • Scheduled Jobs: Automated scripts
  • Events: Trigger automation
  • gs.eventQueue() - Fire event
  • Run in background
  • Use setLimit() for batches
  • Test with "Execute Now"
  • Schedule during off-peak