Mastering Scheduled Jobs in ServiceNow: States, Workflows, and Best Practices

Prathmeshda
Tera Guru

What are Scheduled Jobs in ServiceNow?

Scheduled Jobs in ServiceNow are automated tasks that can be performed on a given time schedule. Scheduled Jobs are very important for automating different administrative tasks. By making use of Scheduled Jobs in ServiceNow, different organizations can improve efficiency and automate different tasks within the organization.

Scheduled Jobs can be used to automate different types of tasks, including:

1)Generation and distribution of reports:Scheduled Jobs can be used to distribute different reports on a day-to-day basis to different stakeholders within an organization.

2)Creation of records based on different templates:Scheduled Jobs can be used to create different records based on different templates. For example, Scheduled Jobs can be used to create incidents based on different templates.

3)Running custom scripts: Scheduled Jobs can be used to run different server-side JavaScripts within an organization.


How do you create a Scheduled Job in ServiceNow?

Creating a Scheduled Job in ServiceNow entails setting the properties of the scheduled job, the schedule, and the action of the scheduled job. The process of creating a Scheduled Job in ServiceNow is as follows:

1.Access Scheduled Jobs: In your ServiceNow instance, access the Scheduled Jobs by going to All > System Definition > Scheduled Jobs.

2.Create New: Click on the 'New' button to create a new scheduled job.

3.Select Job Type: Select the type of scheduled job according to the task you want to automate:

•Automate the generation and distribution of a report.

•Automatically generate something (e.g., a change, an incident, a configuration item) from a template.

•Automatically run a script of your choosing.

4.Name: Provide the name of the scheduled job.

•Active: Check the box to activate the scheduled job. Unchecking the box will deactivate the scheduled job.

•Run: Select the time period of the scheduled job.

•Time/Day: Enter the time or day of the scheduled job.

•Conditional: If checked, a script field appears where you can add a server-side script that returns true or false. The job will only execute if the script returns true.

•Script: If you selected 'Automatically run a script of your choosing' as the job type, this field is where you write the JavaScript code that the scheduled job will execute. This script can interact with ServiceNow APIs, query databases, and perform various operations.

5.Submit/Update: Click Submit to create a new job or Update to save changes to an existing one.

The following is a sample of what the Scheduled Job form looks like in ServiceNow:

scheduled_job_form.png


What are the states of a Scheduled Job?

Scheduled Jobs have different states that they can be in. It is important to understand the different states that a Scheduled Job can be in. The main states that a Scheduled Job can be in are:

Ready - This means that the job is set up and waiting to be executed based on the scheduled time. This state means that the job is active and enabled.

Running - This means that the job is being executed. This state means that the script associated with the job is running.

Queued - This means that the job has been triggered by its schedule but is in the scheduler queue. This means that the job has not been executed because it is waiting for a thread to become available.

Error - This means that there was a problem while executing the job. This state means that there is a problem associated with the script. The error messages can be viewed in the system logs.

What are best practices when utilizing Scheduled Jobs?
To ensure efficient, reliable, and maintainable Scheduled Jobs, consider the following best practices:

Keep Scripts Efficient: Write optimized and performant scripts. Avoid complex queries or operations that could lead to long execution times or performance degradation. Use setLimit() for testing and addQuery() effectively.

•Error Handling and Logging: Implement robust error handling within your scripts. Use gs.log(), gs.info(), or gs.error() to log important information, warnings, and errors. This aids in debugging and monitoring.

•Run As User: Carefully consider the 'Run As' field. For jobs that interact with data not accessible by all users, it's often best to leave 'Run As' empty, allowing the job to run as the system user with elevated privileges. If the job needs to impersonate a specific user for permissions or auditing, specify that user.

•Avoid Hardcoding: Do not hardcode values like sys_ids, URLs, or email addresses directly in scripts. Instead, use system properties, script includes, or configuration tables to store and retrieve these values, making jobs more flexible and easier to maintain across environments.

•Testing: Thoroughly test scheduled jobs in non-production environments before deploying to production. Use the 'Execute Now' button for immediate testing and the Script Debugger for step-by-step debugging.

•Monitoring: Regularly monitor scheduled job execution status and performance. Utilize the 'Scheduled Jobs' module and system logs to identify and address any issues promptly. The 'System Events and Jobs Dashboard' can provide valuable insights.

•Documentation: Document the purpose, functionality, dependencies, and expected outcomes of each scheduled job. This is crucial for future maintenance and troubleshooting.

•Conditional Execution: Leverage the 'Conditional' script field to add an extra layer of control, ensuring the job only runs when specific conditions are met.

•Batch Processing: For large data sets, consider breaking down the task into smaller batches to prevent timeouts and performance issues. This can be achieved by processing a limited number of records in each run and updating a marker for the next run.

•Testing: Testing of scheduled jobs must be carried out in non-production environments before they go live. The 'Execute Now' button is used to test scheduled jobs, while the Script Debugger is used to debug them.

Monitoring: Monitoring of scheduled job execution is necessary. The 'Scheduled Jobs' module is used to monitor scheduled job execution. If there is an issue in scheduled job execution, it is quickly resolved. The 'System Events and Jobs Dashboard' can also provide information.

•Documentation: Documentation of scheduled job functionality is necessary. Documentation of scheduled job functionality is important.

•Conditional Execution: The 'Conditional' script field is used to provide an additional layer of functionality to scheduled job execution.

•Batch Processing: Batch processing is used to avoid timeout issues in scheduled job execution. Batch processing is achieved by processing limited records in scheduled job execution. A marker is created in scheduled job execution to process limited records.

event_queue_flow.png

 

Can Scheduled Jobs trigger a workflow or notification?
Yes, Scheduled Jobs can absolutely trigger workflows and notifications

Triggering Events: Scheduled scripts can use gs.eventQueue() to fire a custom event. This event can then be configured to trigger a notification or a workflow. This is a common pattern for sending out alerts, reminders, or initiating follow-up actions based on scheduled checks.
JavaScript
// Example: Trigger an event to send a notification
 
var gr = new GlideRecord('task');
gr.addQuery('active', true);
gr.addQuery('due_date', '<', gs.nowDateTime());
gr.query();
while (gr.next()) {
// Fire a custom event 'task.overdue' for each overdue task gs.eventQueue('task.overdue', gr, gr.assigned_to.email, gr.number);
}
In this example, the task.overdue event would be defined in System Policy > Events > Registry. A notification (in System Notification > Email > Notifications) or a workflow (in Workflow > Workflow Editor) could then be configured to respond to this event.

•Directly Calling Workflows: Scheduled scripts can directly initiate workflows using the Workflow API. This allows for more complex, multi-step automation processes to be started on a schedule.
JavaScript
// Example: Directly start a workflow from a scheduled job
var wf = new Workflow();
var workflowId = wf.get Workflow ID by Name('My Custom Workflow'); // Replace with your workflow name var currentRecord = new GlideRecord('incident'); // Or any other table relevant to your workflow currentRecord.initialize();
currentRecord.short_description = 'Automated Incident from Scheduled Job';
currentRecord.insert();
wf.startFlow(workflowId, currentRecord, currentRecord.operation(), { 'u_custom_variable': 'value' }); gs.info('Started workflow for incident: ' + currentRecord.number);

•Directly Sending Notifications: While less common for complex scenarios, a scheduled script can directly send an email using gs.sendEmail() or new GlideEmail().send(), though gs.eventQueue() is generally preferred for better maintainability and integration with ServiceNow's notification system.
JavaScript
// Example: Direct email sending (less common, eventQueue preferred) gs.sendEmail('recipient@example.com', 'sender@example.com', 'Scheduled Job Alert', 'This is an automated


If you found this article useful, please mark it as Helpful. It helps others find the content more easily 👍🙂

0 REPLIES 0