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
awaitis 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, norequestJira/requestConfluenceshorthand (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)β
- Forge fires the scheduler trigger periodically (approximately every hour).
- The trigger fetches all enabled scheduled jobs.
- 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.
- If yes, the job ID is pushed to the
scheduled-jobs-queueForge Queue. - The queue listener dequeues the job, fetches its code from storage, and calls
runScript(). runScript()POSTs the script and args to the configured remote Companion App.- The Companion App executes the script and returns
{ result, error, logs }. - 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.
| Global | Type | Description |
|---|---|---|
api | ForgeAPI | Forge API object - use api.asApp().requestJira(...) or api.asApp().requestConfluence(...) |
route | Template-literal tag | Construct safe API route strings: route`/rest/api/3/issue/${id}` |
fetch | (url, options?) => Promise<Response> | Standard fetch for external HTTP calls (non-Atlassian APIs) |
authorize | ForgeAuthorize | Forge authorization utilities |
console | Console | log, 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, andcontextare 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);
Example 2 - Perform a JQL searchβ
/*
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β
-
Always use
api.asApp()- there is no current user in a scheduled job. Calls withoutapi.asApp()will fail. Never useapi.asUser()in this context. -
Never use
requestJira,view,context, orshowFlag- these are frontend globals from Script Console and Fragments. They do not exist in scheduled jobs and will throwReferenceError. -
Use
console.logfor observability - log progress as the job runs, and return a summary object at the end: it is logged as JSON afterreturn:in the job's History. -
Check
response.statusbefore.json()- a failed API call returns a non-JSON error body on 4xx/5xx. Callresponse.text()on error to read the raw message. -
Paginate all list queries - Jira search and Confluence list APIs return at most 50 results by default. Always implement a
startAt/whileloop for operations that need all results. -
Catch errors per item in bulk loops - a single failed update should not abort the entire job. Wrap per-item operations in
try/catchand collect errors separately. -
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. -
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.
-
Do not use Node.js or web platform APIs -
require,import(),process,Buffer,crypto,TextEncoder,AbortController,structuredCloneand the rest of the "Not available" list don't exist in the script's context and throw. -
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.
Useful REST API linksβ
Jira REST API v3β
| Endpoint | Description | Docs |
|---|---|---|
GET /rest/api/3/serverInfo | Instance info | link |
GET /rest/api/3/search/jql?jql=... | Search issues via JQL | link |
GET /rest/api/3/issue/{issueIdOrKey} | Get issue | link |
POST /rest/api/3/issue | Create issue | link |
PUT /rest/api/3/issue/{issueIdOrKey} | Update issue fields | link |
POST /rest/api/3/issue/{issueIdOrKey}/transitions | Transition issue | link |
GET /rest/api/3/issue/{issueIdOrKey}/transitions | List available transitions | link |
POST /rest/api/3/issue/{issueIdOrKey}/comment | Add comment | link |
GET /rest/api/3/project | List projects | link |
GET /rest/api/3/users/search | Search users | link |
GET /rest/api/3/filter | Get filters | link |
GET /rest/api/3/field | List all fields | link |
Confluence REST API v1 / v2β
| Endpoint | Description | Docs |
|---|---|---|
GET /wiki/rest/api/user/current | Current app user info | link |
GET /wiki/rest/api/space | List spaces | link |
GET /wiki/rest/api/content | List pages/blogposts | link |
GET /wiki/rest/api/content/{id} | Get page | link |
POST /wiki/rest/api/content | Create page | link |
PUT /wiki/rest/api/content/{id} | Update page | link |
DELETE /wiki/rest/api/content/{id} | Trash page | link |
GET /wiki/api/v2/pages | List pages (v2) | link |
GET /wiki/api/v2/spaces | List spaces (v2) | link |