Ova

How to Schedule a Script in ServiceNow

Published in ServiceNow Script Scheduling 3 mins read

To schedule a script in ServiceNow, you primarily use Scheduled Script Executions. This feature allows you to automate the running of server-side JavaScript code at specific intervals or times, ensuring your processes run consistently without manual intervention.

Understanding Scheduled Script Executions

A Scheduled Script Execution is a record that defines a script, specifies when it should run, and provides a name for easy identification. Once configured and saved, the ServiceNow platform takes care of executing the script according to your defined schedule.

Step-by-Step Guide to Scheduling a Script

Follow these steps to set up a new Scheduled Script Execution in your ServiceNow instance:

1. Navigate to Scheduled Script Executions

  • From the main ServiceNow navigation filter, type and go to System Definition > Scheduled Script Executions.
  • Click the New button to create a new scheduled job.

2. Configure the Scheduled Job

When the new Scheduled Script Execution form appears, you'll need to fill in several key fields:

  • Name: Give your scheduled job a clear and descriptive name (e.g., "Daily User Account Cleanup," "Monthly Incident Report Generation"). This helps you identify its purpose quickly.
  • Active: Check this box to enable the scheduled job. If unchecked, the job will not run.
  • Run: This crucial field determines when and how often your script will execute. You have several options:
    • Once: Runs only a single time at a specified date and time.
    • Daily: Runs once every day at a specific time.
    • Weekly: Runs once a week on a specific day and time.
    • Monthly: Runs once a month on a specific day of the month and time.
    • Periodically: Runs at a set interval (e.g., every 5 minutes, every 2 hours). This is ideal for tasks requiring frequent execution.
    • On Demand: The script will only run when manually triggered (e.g., by clicking "Execute Now").
  • Time: Depending on your "Run" selection, additional fields like "Time," "Day," "Day of the week," or "Repeat interval" will appear. Configure these to precisely define your schedule.
  • Script: This is where you define the actual JavaScript code that will run. Enter your server-side JavaScript here. Ensure your script is well-tested and robust.

3. Define the Script

In the "Script" field, write your JavaScript logic. This script runs on the server side, giving it access to GlideRecord, GlideSystem, and other server-side APIs.

Example Script:
Here's a simple example that logs a message to the system logs:

gs.info('Scheduled script executed successfully at: ' + gs.nowDateTime());

// Example: Query for Incidents and update a field
var gr = new GlideRecord('incident');
gr.addQuery('state', '6'); // Query for resolved incidents
gr.addQuery('sys_updated_on', '<', gs.daysAgo(30)); // Older than 30 days
gr.query();

while (gr.next()) {
    gr.state = '7'; // Set to Closed
    gr.update();
    gs.info('Incident ' + gr.number + ' closed by scheduled job.');
}

4. Save the Record

  • After filling in all necessary fields and defining your script, click the Submit or Update button (depending on if you're creating a new record or editing an existing one).
  • Once saved, the scheduled job will activate according to your specified schedule.

Key Considerations and Best Practices

When scheduling scripts, keep the following in mind to ensure optimal performance and reliability:

  • Testing: Always test your script thoroughly in a non-production environment before deploying it to production.
  • Logging: Use gs.info(), gs.warn(), or gs.error() statements within your script to log its progress, any issues, or the number of records processed. This helps with debugging and monitoring.
  • Error Handling: Implement try...catch blocks to gracefully handle potential errors in your script, preventing it from failing unexpectedly and providing clear error messages in the logs.
  • Performance:
    • Avoid complex queries or operations that could negatively impact system performance, especially during peak hours.
    • If processing a large number of records, consider using GlideRecord methods like setLimit() or setWorkflow(false) and autoSysFields(false) for efficiency.
  • Scope: Be mindful of the application scope your script runs in. If your script interacts with tables or data outside its scope, you may need to grant appropriate cross-scope access.
  • Alternative Scheduling Methods:
    • Flow Designer: For more visual, low-code automation, Flow Designer can also be used to schedule flows that execute actions, including custom script steps. This often provides more visibility and easier maintenance for non-developers.
    • Workflows: Workflows can include "Timer" activities to pause execution for a set period or until a specific date/time, which can be seen as a form of scheduling within a workflow process.

Types of Scheduled Runs

Here's a table summarizing the different "Run" types for Scheduled Script Executions:

Run Type Description Typical Use Cases
Once Executes a single time at the specified date and time. One-time data cleanup, migration, or setup tasks.
Daily Executes once every day at a specified time. Daily reports, data synchronizations, routine maintenance.
Weekly Executes once a week on a specific day and time. Weekly summary reports, system health checks.
Monthly Executes once a month on a specific day of the month and time. Monthly billing processes, compliance checks, audit reports.
Periodically Executes at a fixed interval (e.g., every 5 minutes, 2 hours). Near real-time integrations, continuous monitoring, cache refreshes.
On Demand Only executes when manually triggered from the record or by another script. Ad-hoc testing, administrator-initiated tasks.

By leveraging Scheduled Script Executions, you can effectively automate a wide range of administrative and data management tasks within your ServiceNow instance, improving efficiency and reducing manual effort.