Scheduled Jobs logo

Scheduled Jobs

Organization
serac-labs
scheduled-jobs

Create ServiceNow scheduled jobs on sysauto_script — daily/weekly cron patterns, batch processing with time/runtime limits, conditional execution, error notifications, and metrics recording.

Overview

Publisherserac-labs
Repositoryserac
Skill namescheduled-jobs
Stars
78
Forks
26
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by serac-labs on GitHub. Read the source before you install it.

Installation

Install the Scheduled Jobs AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/serac-labs/serac.git /tmp/serac
mkdir -p .claude/skills
cp -r /tmp/serac/packages/skills/scheduled-jobs .claude/skills/scheduled-jobs
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Scheduled Jobs in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Scheduled Jobs on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Scheduled Jobs is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Scheduled Jobs for ServiceNow

Scheduled Jobs automate recurring tasks, batch processing, and maintenance operations.

Job Types

TypeTablePurpose
Scheduled Script Executionsysauto_scriptRun custom scripts
Report Schedulersysauto_reportGenerate and email reports
Table Cleanersys_auto_flushDelete old records
LDAP Refreshldap_server_configSync LDAP data
Discoverydiscovery_scheduleNetwork discovery

Scheduled Script Execution (ES5)

Basic Scheduled Job

javascript
// Table: sysauto_script
// Name: Close Stale Incidents
// Run: Daily at 2:00 AM

// Script (ES5 ONLY!):
;(function executeScheduledJob() {
  var LOG_PREFIX = "[CloseStaleIncidents] "
  var closedCount = 0

  // Find incidents inactive for 30 days
  var staleDate = new GlideDateTime()
  staleDate.addDaysLocalTime(-30)

  var gr = new GlideRecord("incident")
  gr.addQuery("state", "IN", "1,2,3") // New, In Progress, On Hold
  gr.addQuery("sys_updated_on", "<", staleDate)
  gr.addQuery("active", true)
  gr.query()

  gs.info(LOG_PREFIX + "Found " + gr.getRowCount() + " stale incidents")

  while (gr.next()) {
    gr.state = 7 // Closed
    gr.close_code = "Closed/Resolved by Caller"
    gr.close_notes = "Auto-closed due to 30 days of inactivity"
    gr.update()
    closedCount++
  }

  gs.info(LOG_PREFIX + "Closed " + closedCount + " stale incidents")
})()

Scheduled Job with Error Handling (ES5)

javascript
// Name: Sync User Data
// Run: Every 6 hours

;(function executeScheduledJob() {
  var LOG_PREFIX = "[SyncUserData] "
  var stats = {
    processed: 0,
    updated: 0,
    errors: 0,
  }

  try {
    // Get users needing sync
    var gr = new GlideRecord("sys_user")
    gr.addQuery("u_needs_sync", true)
    gr.addQuery("active", true)
    gr.setLimit(1000) // Process in batches
    gr.query()

    while (gr.next()) {
      stats.processed++
      try {
        var updated = syncUserFromSource(gr)
        if (updated) {
          stats.updated++
        }
      } catch (e) {
        stats.errors++
        gs.error(LOG_PREFIX + "Error syncing user " + gr.user_name + ": " + e.message)
      }
    }

    gs.info(LOG_PREFIX + "Sync complete: " + JSON.stringify(stats))

    // Send summary email if errors
    if (stats.errors > 0) {
      sendErrorSummary(stats)
    }
  } catch (e) {
    gs.error(LOG_PREFIX + "Job failed: " + e.message)
    notifyAdmins("User sync job failed: " + e.message)
  }

  function syncUserFromSource(userGr) {
    // Sync logic here
    userGr.u_needs_sync = false
    userGr.u_last_sync = new GlideDateTime()
    return userGr.update()
  }

  function sendErrorSummary(stats) {
    gs.eventQueue("user.sync.errors", null, JSON.stringify(stats), "")
  }

  function notifyAdmins(message) {
    gs.eventQueue("system.job.failure", null, message, "")
  }
})()

Batch Processing Job (ES5)

javascript
// Name: Process Large Dataset
// Run: Weekly on Sunday at 1:00 AM

;(function executeScheduledJob() {
  var LOG_PREFIX = "[BatchProcessor] "
  var BATCH_SIZE = 500
  var MAX_RUNTIME = 3600000 // 1 hour in ms
  var startTime = new Date().getTime()

  var processed = 0
  var hasMore = true

  while (hasMore && !isTimeExceeded()) {
    hasMore = processBatch()
  }

  if (hasMore) {
    gs.warn(LOG_PREFIX + "Job stopped due to time limit. Processed: " + processed)
    // Re-queue for next run
    queueContinuation()
  } else {
    gs.info(LOG_PREFIX + "Job complete. Total processed: " + processed)
  }

  function processBatch() {
    var gr = new GlideRecord("u_large_table")
    gr.addQuery("u_processed", false)
    gr.setLimit(BATCH_SIZE)
    gr.query()

    if (!gr.hasNext()) {
      return false
    }

    while (gr.next()) {
      processRecord(gr)
      processed++
    }

    return true
  }

  function processRecord(gr) {
    // Processing logic
    gr.u_processed = true
    gr.u_processed_date = new GlideDateTime()
    gr.update()
  }

  function isTimeExceeded() {
    var elapsed = new Date().getTime() - startTime
    return elapsed > MAX_RUNTIME
  }

  function queueContinuation() {
    // Queue another run
    var job = new GlideRecord("sysauto_script")
    if (job.get("name", "Process Large Dataset - Continuation")) {
      job.next_action = new GlideDateTime()
      job.update()
    }
  }
})()

Schedule Configuration

Run Frequencies

FrequencyCronExample
Every 5 minutes0 */5 * * * ?Health checks
Hourly0 0 * * * ?Data sync
Daily at midnight0 0 0 * * ?Cleanup
Weekly Sunday0 0 0 ? * SUNReports
Monthly 1st0 0 0 1 * ?Billing
CustomVariousSpecific needs

Create Scheduled Job (ES5)

javascript
// Create scheduled job programmatically (ES5 ONLY!)
var job = new GlideRecord("sysauto_script")
job.initialize()
job.setValue("name", "Nightly Cleanup")
job.setValue("active", true)

// Schedule: Daily at 2:00 AM
job.setValue("run_type", "daily")
job.setValue("run_time", "02:00:00")
// Or use explicit schedule
job.setValue("run_dayofweek", "daily")

// Script
job.setValue(
  "script",
  "(function executeScheduledJob() {\n" +
    '    var gr = new GlideRecord("sys_audit_delete");\n' +
    '    gr.addQuery("sys_created_on", "<", gs.daysAgo(90));\n' +
    "    gr.deleteMultiple();\n" +
    '    gs.info("Cleanup complete");\n' +
    "})();",
)

// Run as system
job.setValue("run_as", "") // Empty = System

job.insert()

Conditional Execution

javascript
// Job that checks conditions before running (ES5 ONLY!)
;(function executeScheduledJob() {
  var LOG_PREFIX = "[ConditionalJob] "

  // Check if job should run
  if (!shouldRun()) {
    gs.info(LOG_PREFIX + "Skipping execution - conditions not met")
    return
  }

  // Execute main logic
  executeMainTask()

  function shouldRun() {
    // Check business hours
    var now = new GlideDateTime()
    var hour = parseInt(now.getLocalTime().getByFormat("HH"), 10)

    // Only run outside business hours (before 6am or after 8pm)
    if (hour >= 6 && hour < 20) {
      return false
    }

    // Check for active change freeze
    var freeze = new GlideRecord("change_request")
    freeze.addQuery("type", "freeze")
    freeze.addQuery("state", "implement")
    freeze.query()

    if (freeze.hasNext()) {
      gs.info(LOG_PREFIX + "Change freeze active")
      return false
    }

    return true
  }

  function executeMainTask() {
    // Main job logic here
    gs.info(LOG_PREFIX + "Executing main task")
  }
})()

Job Monitoring

Check Job Status (ES5)

javascript
// Query scheduled job history (ES5 ONLY!)
var history = new GlideRecord("sys_trigger")
history.addQuery("name", "CONTAINS", "Nightly Cleanup")
history.orderByDesc("sys_created_on")
history.setLimit(10)
history.query()

while (history.next()) {
  gs.info(
    "Job: " +
      history.getValue("name") +
      " | State: " +
      history.getValue("state") +
      " | Next: " +
      history.getValue("next_action"),
  )
}

Job with Metrics (ES5)

javascript
// Job that records performance metrics (ES5 ONLY!)
;(function executeScheduledJob() {
  var LOG_PREFIX = "[MetricsJob] "
  var startTime = new Date().getTime()
  var metrics = {
    startTime: new GlideDateTime().getDisplayValue(),
    recordsProcessed: 0,
    errors: 0,
  }

  try {
    // Main processing
    var gr = new GlideRecord("incident")
    gr.addQuery("active", true)
    gr.query()

    while (gr.next()) {
      processRecord(gr)
      metrics.recordsProcessed++
    }
  } catch (e) {
    metrics.errors++
    gs.error(LOG_PREFIX + "Error: " + e.message)
  } finally {
    // Record metrics
    metrics.endTime = new GlideDateTime().getDisplayValue()
    metrics.duration = (new Date().getTime() - startTime) / 1000
    recordMetrics(metrics)
  }

  function processRecord(gr) {
    // Processing logic
  }

  function recordMetrics(metrics) {
    var metricsRecord = new GlideRecord("u_job_metrics")
    metricsRecord.initialize()
    metricsRecord.setValue("u_job_name", "MetricsJob")
    metricsRecord.setValue("u_start_time", metrics.startTime)
    metricsRecord.setValue("u_end_time", metrics.endTime)
    metricsRecord.setValue("u_duration", metrics.duration)
    metricsRecord.setValue("u_records_processed", metrics.recordsProcessed)
    metricsRecord.setValue("u_errors", metrics.errors)
    metricsRecord.insert()

    gs.info(LOG_PREFIX + "Metrics: " + JSON.stringify(metrics))
  }
})()

MCP Tool Integration

Available Tools

ToolPurpose
snow_schedule_jobCreate scheduled job
snow_artifact_manage (action=find)Find existing jobs
snow_execute_scriptTest job script
snow_get_logsCheck job execution logs

Example Workflow

javascript
// 1. Create scheduled job
await snow_schedule_job({
  name: "Daily Report Generator",
  run_type: "daily",
  run_time: "06:00:00",
  script: "/* report generation script */",
  active: true,
})

// 2. Test the script
await snow_execute_script({
  script: "/* test job script */",
})

// 3. Check logs
await snow_get_logs({
  filter: 'message CONTAINS "Daily Report"',
  limit: 50,
})

Best Practices

  1. Logging - Comprehensive logging for debugging
  2. Error Handling - Try-catch with notifications
  3. Batching - Process large datasets in batches
  4. Time Limits - Check runtime to prevent timeouts
  5. Off-Peak - Schedule during low-usage periods
  6. Idempotent - Safe to run multiple times
  7. Monitoring - Record metrics and status
  8. ES5 Only - No modern JavaScript syntax

Frequently asked questions

What does the Scheduled Jobs AI skill do?

Create ServiceNow scheduled jobs on sysauto_script — daily/weekly cron patterns, batch processing with time/runtime limits, conditional execution, error notifications, and metrics recording.

Why use Scheduled Jobs on TypingMind?

Because you install it once and use it with any model. Scheduled Jobs is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Scheduled Jobs in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/serac-labs/serac/tree/main/packages/skills/scheduled-jobs. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Scheduled Jobs?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Scheduled Jobs?

As many as you like. As long as a model supports skills, you can use Scheduled Jobs with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Scheduled Jobs AI skill free?

Yes. It is published on GitHub by serac-labs under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇