Skip to main content

Scheduled Jobs API reference for AI

This document is a complete API reference and code guide for writing scripts that run in Script Master's Scheduled Jobs module - an Atlassian Forge app that lets users define backend JavaScript functions executed on a cron schedule, automating recurring tasks like syncing data, enforcing governance rules, generating reports, or triggering external integrations in Jira and Confluence.

Use this document as context when asking an AI assistant (Claude, Gemini, ChatGPT, etc.) to generate Scheduled Job scripts:

Here is the API reference: https://docs.apportunity.xyz/script-master/code-editor/scheduled-jobs-ai-prompt. Build a scheduled job script for Script Master that [your task].


Execution model​

Scripts run as async JavaScript functions executed on the Forge backend (Node.js, ARM64). This is a server-side FaaS environment - not a browser and not the user's machine. Your script code is wrapped like this:

// Runs with vm.runInNewContext. The context's globals are api, route, fetch, authorize, console
// and the other globals listed under "Available globals".
"use strict";
(async () => {
// YOUR SCRIPT CODE HERE
})();

Key implications:

  • Top-level await is supported - use it freely.
  • The return value of the script is captured and appears in the execution log as return: <value>. There is no HTTP response to construct - return data for debugging.
  • console.log() / console.info() / console.warn() / console.error() are captured and stored in the job's invocation log. Maximum 100 log entries per run; each entry capped at 2 048 characters.
  • Errors thrown by the script are caught and recorded in the log.
  • Scripts run as the app (not as the current user) - always use api.asApp() for all Atlassian API calls.
  • No browser APIs, no window, no DOM, no requestJira/requestConfluence shorthand (those are Script Console-only frontend globals).
  • Execution requires a configured Companion App for remote execution. Without it, scripts will not run and will log an error - see Set up the Companion App.

Scheduling and timing​

Forge triggers fire the scheduler once per hour. Cron expressions are read in UTC. For each enabled job, the scheduler remembers the last scheduled time it already queued. If the job's most recent scheduled time is newer than that, the job is queued once. This means:

  • Minimum real-world interval is approximately 1 hour, regardless of the cron expression.
  • Cron expressions with sub-hourly intervals (for example, */15 * * * *) are valid but the job still runs only once per scheduler run, about once an hour. Missed occurrences are not caught up one by one.
  • A job can start up to an hour after its scheduled time, and Forge queue processing can add more delay.
  • A new job doesn't run for a scheduled time that passed before the scheduler first saw it.
  • A site can have up to 5 scheduled jobs.
  • A job can also be triggered manually from the dashboard using the Run button, which bypasses scheduling and queues the job immediately.

Execution flow (for production runs)​

  1. Forge fires the scheduler trigger periodically (approximately every hour).
  2. The trigger fetches all enabled scheduled jobs.
  3. For each job, it parses the cron expression (in UTC) and checks whether the most recent scheduled time is newer than the last one it queued for that job.
  4. If yes, the job ID is pushed to the scheduled-jobs-queue Forge Queue.
  5. The queue listener dequeues the job, fetches its code from storage, and calls runScript().
  6. runScript() POSTs the script and args to the configured remote Companion App.
  7. The Companion App executes the script and returns { result, error, logs }.
  8. The result and logs are persisted to the job's invocation history (visible in the job's History).

Execution flow (for test runs from the UI)​

When you select Test in the editor, the ScheduledJobs.Test resolver is invoked directly with a 24-second timeout. This runs synchronously against the companion app and returns output immediately to the test panel.


Available globals​

Scheduled job scripts are backend functions. The available globals are the same on both Jira and Confluence - there are no platform-specific globals.

GlobalTypeDescription
apiForgeAPIForge API object - use api.asApp().requestJira(...) or api.asApp().requestConfluence(...)
routeTemplate-literal tagConstruct safe API route strings: route`/rest/api/3/issue/${id}`
fetch(url, options?) => Promise<Response>Standard fetch for external HTTP calls (non-Atlassian APIs)
authorizeForgeAuthorizeForge authorization utilities
consoleConsolelog, info, warn, error - output captured in the invocation log

Other globals the Companion App passes: setTimeout, setInterval, setImmediate, clearTimeout, clearInterval, atob, btoa, encodeURI, encodeURIComponent, decodeURI, decodeURIComponent, isFinite, isNaN, parseFloat, parseInt, Array, Promise, String, Set, Boolean, Number, Map, JSON, Intl, Math, RegExp, Error, Date, URL, URLSearchParams.

JavaScript built-ins: the script runs in its own JavaScript context (Node's vm module, in strict mode), so the language's own built-in objects are there too, for example Object, Symbol, BigInt, WeakMap, WeakSet, ArrayBuffer, DataView, typed arrays and Reflect.

Not available: everything from Node.js or the web platform that isn't listed above. For example require, process, module, Buffer, crypto, TextEncoder, TextDecoder, AbortController, AbortSignal, structuredClone and queueMicrotask don't exist and throw a ReferenceError, and import() fails. Use atob/btoa for Base64.

Note: requestJira, requestConfluence, requestBitbucket, view, showFlag, and context are not available in scheduled jobs. Those globals exist only in Script Console (frontend) and Fragments (frontend).


API reference​

api​

The Forge API object from @forge/api. The primary usage pattern is api.asApp() which returns a client that acts as the installed app (with its declared OAuth scopes), not as any individual user.

api.asApp().requestJira(route: RouteString, options?: RequestInit): Promise<Response>
api.asApp().requestConfluence(route: RouteString, options?: RequestInit): Promise<Response>

Both methods return a standard Response object. Always call .json() or .text() on it to read the body.

Example - Jira:

const response = await api.asApp().requestJira(route`/rest/api/3/serverInfo`, {
headers: { 'Accept': 'application/json' }
});
const data = await response.json();
console.log('status', response.status);
console.log('data', data);

Example - Confluence:

const response = await api.asApp().requestConfluence(route`/wiki/rest/api/space`, {
headers: { 'Accept': 'application/json' }
});
const data = await response.json();
console.log('spaces', data.results?.length);

route​

A tagged template literal that constructs safe URL route strings. It encodes any interpolated values to prevent URL injection. Always use route when building paths with dynamic values.

// Safe - encodes the variable
const issueKey = 'TEST-123';
route`/rest/api/3/issue/${issueKey}`

// Also valid for static paths
route`/rest/api/3/serverInfo`

fetch​

Standard Fetch API for calling external (non-Atlassian) HTTP endpoints. Not needed for Jira or Confluence - use api.asApp().requestJira() / api.asApp().requestConfluence() for those.

const response = await fetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
});
const data = await response.json();
console.log('external response', data);

console​

All four standard methods are captured in the invocation log:

console.log('message', someObject);
console.info('info message');
console.warn('warning');
console.error('error details', error);

Log entries are limited to 100 per run. Each entry is truncated at 2 048 characters. Log entries from production runs are kept in the job's History (the last 10 runs). Log entries from test runs appear in the test output panel.


Code patterns​

Pattern 1 - Paginate through all Jira issues​

Jira search returns one page of issues per request. Use nextPageToken to paginate (/rest/api/3/search/jql doesn't support startAt).

const jql = 'project = "MY-PROJECT" AND status = "To Do"';
const maxResults = 50;
const allIssues = [];
let nextPageToken;

do {
const response = nextPageToken
? await api.asApp().requestJira(
route`/rest/api/3/search/jql?jql=${jql}&maxResults=${maxResults}&fields=summary&nextPageToken=${nextPageToken}`,
{ headers: { 'Accept': 'application/json' } }
)
: await api.asApp().requestJira(
route`/rest/api/3/search/jql?jql=${jql}&maxResults=${maxResults}&fields=summary`,
{ headers: { 'Accept': 'application/json' } }
);
const data = await response.json();

allIssues.push(...(data.issues ?? []));
nextPageToken = data.nextPageToken;
} while (nextPageToken);

console.log('total found', allIssues.length);
return allIssues.map(i => i.key);

Pattern 2 - Error handling per item in bulk operations​

When processing multiple items, catch per-item errors so one failure does not abort the entire run.

const issues = ['TEST-1', 'TEST-2', 'TEST-3'];
const results = { success: [], failed: [] };

for (const key of issues) {
try {
const response = await api.asApp().requestJira(route`/rest/api/3/issue/${key}`, {
method: 'PUT',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ fields: { priority: { name: 'High' } } })
});
if (response.status >= 400) {
const err = await response.text();
results.failed.push({ key, error: err });
} else {
results.success.push(key);
}
} catch (err) {
results.failed.push({ key, error: String(err) });
}
}

console.log('success', results.success.join(', '));
console.log('failed', results.failed.map(f => `${f.key}: ${f.error}`).join('\n'));
return results;

Pattern 3 - Check response status before parsing JSON​

Always check response.status before calling .json(). A 4xx/5xx response body may not be valid JSON.

const response = await api.asApp().requestJira(route`/rest/api/3/issue/TEST-999`, {
headers: { 'Accept': 'application/json' }
});

if (!response.ok) {
const errorText = await response.text();
console.error('API error', response.status, errorText);
return { error: response.status, details: errorText };
}

const issue = await response.json();
console.log('summary', issue.fields.summary);
return issue;

Pattern 4 - Return structured output for easy log reading​

Return an object with named fields rather than a primitive. The return value is logged as return: <value>, with objects and arrays written as indented JSON, so a summary object reads well in the invocation log.

const summary = {
processed: 42,
updated: 38,
skipped: 4,
errors: [],
};

// Logged as indented JSON after "return:" in the invocation log
return summary;

Complete examples​

Example 1 - Jira REST API (check server info)​

/* no import needed - 'api', 'route', 'fetch', 'authorize' already available as global variables */

const response = await api.asApp().requestJira(route`/rest/api/3/serverInfo`, {
headers: {
'Accept': 'application/json'
}
});

const responseData = await response.json();

console.log('responseData', responseData);

/*
This is an example of getting issues using JQL.
Read more about Jira Query Language (JQL) here:
https://support.atlassian.com/jira-service-management-cloud/docs/use-advanced-search-with-jira-query-language-jql/
Learn more about the REST API in this example here:
https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-search/#api-rest-api-3-search-jql-get
*/
const jql = 'created > -7d'; // JQL: get all the issues created last 7 days

const response = await api.asApp().requestJira(route`/rest/api/3/search/jql?jql=${jql}&fields=summary`, {
headers: {
'Accept': 'application/json'
}
});
const issuesResponse = await response.json();

// Return all issue keys for the specified JQL
const foundIssueKeys = issuesResponse.issues.map((issue) => issue.key).join(', ');

console.log('foundIssueKeys', foundIssueKeys);

Example 3 - Fetch external resources​

/*
Fetch External Resources
In this example, we demonstrate how to use the fetch function to access any external REST API.
Specifically, we will request the complete list of available apps from the Atlassian Marketplace.
*/
const response = await fetch('https://marketplace.atlassian.com/rest/2/addons/vendor/467796300');
const data = await response.json();

console.log('Best apps:', data);

Example 4 - Forge Bridge API globals (Confluence)​

/* no import needed - 'api', 'route', 'fetch', 'authorize' already available as global variables */

console.log(typeof api !== 'undefined' && api ? 'api is defined' : 'api is undefined');
console.log(typeof route !== 'undefined' && route ? 'route is defined' : 'route is undefined');
console.log(typeof fetch !== 'undefined' && fetch ? 'fetch is defined' : 'fetch is undefined');
console.log(typeof authorize !== 'undefined' && authorize ? 'authorize is defined' : 'authorize is undefined');

Example 5 - Confluence REST API​

/* no import needed - 'api', 'route', 'fetch', 'authorize' already available as global variables */

const response = await api.asApp().requestConfluence(route`/wiki/rest/api/user/current`, {
headers: {
'Accept': 'application/json'
}
});

const responseData = await response.json();

console.log('responseData', responseData);

return responseData;

Example 6 - Bulk transition stale Jira issues​

/*
Close all issues in project KEY that have been open and unupdated for more than 90 days.
Customize: jql, transitionId (get from /rest/api/3/issue/{key}/transitions).
*/
const jql = 'project = "KEY" AND status != Done AND updated < -90d';
const transitionId = '31'; // Get this from the transitions API for your workflow

const processed = [];
const errors = [];

// Transitioned issues drop out of the JQL result, so each pass searches again from the start.
// Stop when a pass finds nothing new, so issues that can't be transitioned don't loop forever.
while (true) {
const searchResp = await api.asApp().requestJira(
route`/rest/api/3/search/jql?jql=${jql}&maxResults=50&fields=summary,status`,
{ headers: { 'Accept': 'application/json' } }
);
const searchData = await searchResp.json();
const pending = (searchData.issues ?? []).filter(issue => !processed.includes(issue.key) && !errors.some(e => e.startsWith(`${issue.key}:`)));
if (!pending.length) break;

for (const issue of pending) {
const transResp = await api.asApp().requestJira(
route`/rest/api/3/issue/${issue.key}/transitions`,
{
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ transition: { id: transitionId } })
}
);
if (transResp.status === 204) {
processed.push(issue.key);
} else {
const errText = await transResp.text();
errors.push(`${issue.key}: ${errText}`);
}
}

}

console.log('transitioned', processed.join(', '));
if (errors.length) console.error('errors', errors.join('\n'));
return `transitioned=${processed.length}, errors=${errors.length}`;

Example 7 - Post a daily summary to an external webhook (Slack, Teams, etc.)​

/*
Every day, count open high-priority issues and post a summary to an external webhook.
Set WEBHOOK_URL to your Slack/Teams/other incoming webhook URL.
*/
const WEBHOOK_URL = 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL'; // ← configure this
const jql = 'priority in (Highest, High) AND status != Done';

const searchResp = await api.asApp().requestJira(
route`/rest/api/3/search/approximate-count`,
{
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({ jql })
}
);
const searchData = await searchResp.json();
const count = searchData.count;

const message = { text: `*Open high-priority issues:* ${count}` };

const webhookResp = await fetch(WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(message)
});

console.log('webhook status', webhookResp.status);
return `posted count=${count}, webhook=${webhookResp.status}`;

Writing good scripts - Rules​

  1. Always use api.asApp() - there is no current user in a scheduled job. Calls without api.asApp() will fail. Never use api.asUser() in this context.

  2. Never use requestJira, view, context, or showFlag - these are frontend globals from Script Console and Fragments. They do not exist in scheduled jobs and will throw ReferenceError.

  3. Use console.log for observability - log progress as the job runs, and return a summary object at the end: it is logged as JSON after return: in the job's History.

  4. Check response.status before .json() - a failed API call returns a non-JSON error body on 4xx/5xx. Call response.text() on error to read the raw message.

  5. Paginate all list queries - Jira search and Confluence list APIs return at most 50 results by default. Always implement a startAt / while loop for operations that need all results.

  6. Catch errors per item in bulk loops - a single failed update should not abort the entire job. Wrap per-item operations in try/catch and collect errors separately.

  7. Remember the 60-minute timing floor - even a * * * * * cron expression will only execute approximately once per hour due to how Forge triggers work. Do not design logic that depends on sub-hourly precision.

  8. Respect the 5-job limit - each site supports a maximum of 5 scheduled jobs in Script Master. Design jobs to be composable (one job can handle multiple tasks internally) rather than creating many single-purpose jobs.

  9. Do not use Node.js or web platform APIs - require, import(), process, Buffer, crypto, TextEncoder, AbortController, structuredClone and the rest of the "Not available" list don't exist in the script's context and throw.

  10. Always configure a Companion App - local execution is not supported. If a Companion App is not configured, every run will fail with "Running scripts locally is not supported in this version of Script Master". The test panel will show this error before running any code.


Jira REST API v3​

EndpointDescriptionDocs
GET /rest/api/3/serverInfoInstance infolink
GET /rest/api/3/search/jql?jql=...Search issues via JQLlink
GET /rest/api/3/issue/{issueIdOrKey}Get issuelink
POST /rest/api/3/issueCreate issuelink
PUT /rest/api/3/issue/{issueIdOrKey}Update issue fieldslink
POST /rest/api/3/issue/{issueIdOrKey}/transitionsTransition issuelink
GET /rest/api/3/issue/{issueIdOrKey}/transitionsList available transitionslink
POST /rest/api/3/issue/{issueIdOrKey}/commentAdd commentlink
GET /rest/api/3/projectList projectslink
GET /rest/api/3/users/searchSearch userslink
GET /rest/api/3/filterGet filterslink
GET /rest/api/3/fieldList all fieldslink

Confluence REST API v1 / v2​

EndpointDescriptionDocs
GET /wiki/rest/api/user/currentCurrent app user infolink
GET /wiki/rest/api/spaceList spaceslink
GET /wiki/rest/api/contentList pages/blogpostslink
GET /wiki/rest/api/content/{id}Get pagelink
POST /wiki/rest/api/contentCreate pagelink
PUT /wiki/rest/api/content/{id}Update pagelink
DELETE /wiki/rest/api/content/{id}Trash pagelink
GET /wiki/api/v2/pagesList pages (v2)link
GET /wiki/api/v2/spacesList spaces (v2)link

Forge references​