Describes utilities in the Javascript API to handle background jobs.

sys.jobs

This package contains methods to handle background jobs.

findById(id)

Finds a background job by its ID.

Parameters

Name Type Required Default Description

id

string

yes

ID of the job.

Returns

sys.jobs.Job - The job object or null if not found.

Exceptions

badRequest

If id is not a valid ID.

Samples

// executes an action in the background and finds the job for it

var jobId = sys.data.executeAction('companies', {type: 'a'}, 'logSomething', {param1: 'a', param2: 'b'});
var job = sys.jobs.findById(jobId);
log('job: '+job.name());

find(query)

Finds jobs using a query. A query looks like this:

var query = {};
query['status'] = 'FINISHED';
query['_size'] = 50;

Valid parameters are:

  • type: the type of job. You can specify many separated by commas. Only job types you can use in your code are:
    • IMPORT_RECORDS
    • EXPORT_RECORDS
    • EXECUTE_ACTION
    • DELETE_RECORDS
    • EXECUTE_LISTENER
    • IMPORT_USERS
    • EXPORT_USERS
    • STOP_APP
    • START_APP
    • DEPLOY_ENDPOINT
    • UNDEPLOY_ENDPOINT
  • status: the status of the job. Valid values are: PENDING, RUNNING, FINISHED, STOPPING, STOPPED, and CANCELED. You can specify many statuses separated by comma.
  • startFrom: filter by the date the job started, combined with startTo (as a range) or alone (in milliseconds).
  • startTo: filter by the date the job started, combined with startFrom (as a range) or alone (in milliseconds).
  • endFrom: filter by the date the job ended, combined with endTo (as a range) or alone (in milliseconds).
  • endTo: filter by the date the job ended, combined with endFrom (as a range) or alone (in milliseconds).
  • createFrom: filter by the date the job was created, combined with createTo (as a range) or alone (in milliseconds).
  • createTo: filter by the date the job was created, combined with createFrom (as a range) or alone (in milliseconds).
  • hasErrors: if the job has errors. You can pass true or false.
  • _size: maximum number of jobs to retrieve.

Parameters

Name Type Required Default Description

query

object

yes

The query to filter jobs.

Returns

sys.commons.ResultSet - The jobs matching the query ordered by creation time in descendent order.

Exceptions

badRequest

If query is invalid.

Samples

// finds jobs finished with errors

var jobs = sys.jobs.find({status: 'FINISHED', hasErrors: 'true', _size: 10});
while (jobs.hasNext()) {
  var job = jobs.next();
  log('job with errors: '+job.name());
}

logs(jobId, query)

Retrieves logs for a background job. You can add some filters and paginate them.

Parameters

Name Type Required Default Description

jobId

string

yes

ID of the job to retrieve its logs.

query

object

yes

Query to filter logs. Valid options are:

  • level: the level of the job. Allowed values are: INFO and ERROR.
  • message: a string that will be matched partially with the message of the log.
  • from: The minimum timestamp in milliseconds since Epoch. If you specify this parameter, period will be ignored.
  • to: The maximum timestamp in milliseconds since Epoch. If you specify this parameter, period will be ignored.
  • period: you can specify a period of time. Valid values are today, yesterday or a time duration like 2h 30m or 10m, where you should read logs in the last X amount of time.
  • _size: maximum number of logs to retrieve.

Returns

sys.commons.ResultSet - A result set with the logs matching the query.

Exceptions

badRequest

If jobId or query are invalid.

notFound

If no job is found with the given ID.

Samples

// prints up to 10 logs for the last 3 jobs

var jobs = sys.jobs.find({status: 'FINISHED', _size: 3});
while (jobs.hasNext()) {
  var job = jobs.next();
  var logs = sys.jobs.logs(job.id(), {_size: 10});
  log('logs for job ['+job.name()+']');
  while (logs.hasNext()) {
    var logEntry = logs.next();
    log('   '+logEntry.level()+': '+logEntry.message());
  }
}

logInfo(jobId, message)

Adds a log to the job with the INFO level.

If you don’t send the parameter jobId, the current job will be used. If there isn’t current job, the log will be discarded silently.

Parameters

Name Type Required Default Description

jobId

string

no

ID of the job to add the log. If you don’t send this parameter, the current job will be used. If there isn’t current job, the log will be discarded silently.

message

string

yes

The message to log.

Exceptions

badRequest

If jobId or message are invalid.

notFound

If no job is found with the given ID.

Samples

// adds a log to the last 3 jobs

var jobs = sys.jobs.find({_size: 3});
while (jobs.hasNext()) {
  var job = jobs.next();
  sys.jobs.logInfo(job.id(), "this is a test log!");
}

logError(jobId, message)

Adds a log to the job with the ERROR level. Keep in mind that adding an error log will set the error flag in the job.

If you don’t send the parameter jobId, the current job will be used. If there isn’t current job, the log will be discarded silently.

Parameters

Name Type Required Default Description

jobId

string

no

ID of the job to add the log. If you don’t send this parameter, the current job will be used. If there isn’t current job, the log will be discarded silently.

message

string

yes

The message to log.

Exceptions

badRequest

If jobId or message are invalid.

notFound

If no job is found with the given ID.

Samples

// adds a log to the last 3 jobs

var jobs = sys.jobs.find({_size: 3});
while (jobs.hasNext()) {
  var job = jobs.next();
  sys.jobs.logError(job.id(), "adds an error log!");
}

waitForJob(jobId, desiredStatus, maxTimeToWait)

Waits for a job to reach specified status. It returns when the job reaches the one of the specified statuses or it will throw a timeout exception if maximum wait time is reached.

Parameters

Name Type Required Default Description

jobId

string

yes

The ID of the job to wait for.

desiredStatus

string or string[]

yes

The desried status of the job. You pass an array with many statuses.

Valid statuses are: PENDING, RUNNING, FINISHED, STOPPING, STOPPED, CANCELING and CANCELED.

maxTimeToWait

number

yes

Maximum time to wait for the job to get into one of the statuses specified in desiredStatus. If the job takes longer a timeout exception will be thrown.

Exceptions

badRequest

If jobId or desiredStatus are invalid.

notFound

If no job is found with the given ID.

timeout

If the job took longer than maxTimeToWait to get into one of the desired statuses.

Samples

// executes an action in the background and waits for its completion

var jobId = sys.data.executeAction('companies', {}, 'logSomething', {param1: 'a', param2: 'b'});
try {
  sys.jobs.waitForJob(jobId, 'FINISHED', 60000);
  log('job finished!!!');
} catch (e) {
  if (sys.exceptions.getCode(e) == 'timeout') {
    log('timeout execution the job');
  }
}

// executes an action in the background and waits until it is finished or stopped

var jobId = sys.data.executeAction('companies', {}, 'logSomething', {param1: 'a', param2: 'b'});
try {
  sys.jobs.waitForJob(jobId, ['FINISHED', 'STOPPED'], 60000);
  log('job finished!!!');
} catch (e) {
  if (sys.exceptions.getCode(e) == 'timeout') {
    log('timeout execution the job');
  }
}

setLowPriority(jobId)

Sets the low priority flag for job. This means if there are other jobs running they will have more priority than this one.

Parameters

Name Type Required Default Description

jobId

string

yes

The ID of the job to flag as low priority.

Exceptions

badRequest

If jobId is invalid.

notFound

If no job is found with the given ID.

Samples

// executes an action in the background and sets the low priority flag

var jobId = sys.data.executeAction('companies', {}, 'logSomething', {param1: 'a', param2: 'b'});
sys.jobs.setLowPriority(jobId);
log('job flagged as low priority');

removeLowPriority(jobId)

Removes the low priority flag from the job.

Parameters

Name Type Required Default Description

jobId

string

yes

The ID of the job to remove low priority flag.

Exceptions

badRequest

If jobId is invalid.

notFound

If no job is found with the given ID.

Samples

// executes an action in the background and sets the low priority flag and the removes it

var jobId = sys.data.executeAction('companies', {}, 'logSomething', {param1: 'a', param2: 'b'});
sys.jobs.setLowPriority(jobId);
log('job flagged as low priority');
sys.jobs.removeLowPriority(jobId);
log('job unflagged as low priority');

getCurrentJobId()

Returns the ID of the job the scripts is running on. If the script isn’t running inside a job this method will return null.

Returns

string - The ID of the current job or null if the script isn’t running inside a job.

Samples

// logs the ID of the job executing the script

var jobId = sys.jobs.getCurrentJobId();
log('job id: ' + jobId);

getCurrentJob()

Returns the job the scripts is running on. If the script isn’t running inside a job this method will return null.

Returns

sys.jobs.Job - The job or null if the script isn’t running inside a job.

Samples

// logs the name of the job executing the script

var job = sys.jobs.getCurrentJob();
log('job id: ' + job.label());

sys.jobs.Job

Contains information about the job.

id()

Returns the ID of the job.

Returns

string - The ID of the job

label()

Returns the label of the job.

Returns

string - The label of the job.

type()

Returns the type of the job. The only type of jobs that you can use in your code are the following ones:

  • IMPORT_RECORDS
  • EXPORT_RECORDS
  • EXECUTE_ACTION
  • DELETE_RECORDS
  • EXECUTE_LISTENER
  • IMPORT_USERS
  • EXPORT_USERS
  • STOP_APP
  • START_APP
  • DEPLOY_ENDPOINT
  • UNDEPLOY_ENDPOINT

There are more type of jobs but they are system ones and can change or be removed without notice.

Returns

string - The type of the job

status()

Returns the current status of the job. Possible values are:

  • PENDING: the job is pending for execution.
  • RUNNING: the job is being executed.
  • FINISHED: the job is completed.
  • STOPPING: the job is stopping. This could take a while until the job can be stopped gracefully.
  • STOPPED: the job has been stopped but can be resumed.
  • CANCELED: the job has been canceled and cannot be resumed. .

Returns

string - The current status of the job.

progress()

Returns the percentage of progress of the job. Keep in mind that in some jobs it might not very precise.

Returns

number - The progress of the job.

waiting()

Returns the amount of time in milliseconds since the job was created until execution started. If it is still in pending this value will grow.

Returns

number - The number of milliseconds that the job has been waiting.

duration()

Returns the amount of time in milliseconds the job took to complete its execution since start date. If it is still in progress this value will grow.

Returns

number - The number of milliseconds that the job has been executing.

hasErrors()

Indicates if there have been errors during the execution of the job.

Returns

boolean - true if there have been errors, false otherwise.

startDate()

Returns the date where the job started its execution. Keep in mind that a job could be in pending for a long time if there is a heavy load on the app. In that case start date might be null and it will be set when the job is actually executed.

Returns

Date - The date when the execution of the job started

endDate()

Returns the date where the job finished its execution. It could be because the job finished correctly or because it was stopped.

Returns

Date - The date when the execution of the job finished

runBy()

Returns an Record object with the information of the user that triggered the job.

Returns

object - Object with ID and name of the user.

data()

Returns an object that contains the parameters of a job. This depends on the type of job and should only be used in public jobs:

Start app

Path Description

pushChanges

true if changes will be pushed during the starting of the app. false or empty otherwise.

wakingUp

true if the app was sleeping and is waking ap. false otherwise.

Import records

Path Description

fileName

This is the name of the file that will be imported.

entityName

The name of the entity where records will be imported.

Export records

Path Description

entityName

The name of the entity where records will be exported from.

Delete records

Path Description

entityName

The name of the entity where records will be deleted from.

Execute action

Path Description

entityName

The name of the entity the action belongs to.

actionName

The name of the action to be executed.

Execute listener

Path Description

listenerName

The name of the listener to execute.

Import users

Path Description

fileName

This is the name of the file that will be imported.

notifyUsers

true if people will be notified by email when users are created; false otherwise.

Deploy endpoint

Path Description

endpointName

The name of the endpoint to deploy.

Undeploy endpoint

Path Description

endpointName

The name of the endpoint to undeploy.

Returns

object - The parameters of the job.

results()

Returns an object that contains the results of executing the job. This depends on the type of job and should only be used in public jobs:

Import records

Path Description

rowsImported

The number of rows that were imported successfully.

rowsWithErrors

The number of rows that couldn’t be imported due to errors.

Export records

Path Description

fileLink

URL to download the CSV file with the exported records. You will need to send the token in the headers in order to be able to download it.

fileId

The ID of the file that was generated.

recordsExported

The number of records that were exported.

Delete records

The result will be a map like this one:

{
  "results": {
    "id1": {
      "status": "ok"
    },
    "id2": {
      "status": "error",
      "errorMessage": "error message"
    }
  }
}

status will indicate if the delete process was executed successfully over that record (ok) or if there were errors (error). The field response will be available only if the action is configured to return the response in the results; otherwise it won’t be there.

One important thing to keep in mind is that the maximum number of responses in this map will be 1,000. If you execute the delete process over more than 1,000 records you might not be able to collect the response for each one.

Execute action

The results of this job depends on the type of action. If the action is of type One record, the result will be a map like this one:

{
  "results": {
    "id1": {
      "status": "ok",
      "response": "response from action"
    },
    "id2": {
      "status": "error",
      "errorMessage": "error message"
    }
  }
}

status will indicate if the action was executed successfully over that record (ok) or if there were errors (error). The field response will be available only if the action is configured to return the response in the results; otherwise it won’t be there. The field errorMessage will be present when there is an error, giving some insight about the problem.

One important thing to keep in mind is that the maximum number of responses in this map will be 1,000. If you execute the action over more than 1,000 records you might not be able to collect the response for each one.

If the action is of type Many records, you will only get a map with fields status and response:

{
  "results": {
    "status": "ok",
    "response": "response from action"
  }
}

Import users

Path Description

Export users

Path Description

fileLink

URL to download the CSV file with the exported users. You will need to send the token in the headers in order to be able to download it.

fileId

The ID of the file that was generated.

usersExported

The number of users that were exported.

Returns

object - The results of the job.

logs()

Returns the logs of the job. It accepts a query as parameter. This method works exactly the same as sys.jobs.logs(), so check its documentation to understand how it works.

Returns

sys.commons.ResultSet - A result set with the logs of the job.

Exceptions

notFound

If job is not found in the database.

logInfo(message)

Adds a log to the job with the INFO level.

Parameters

Name Type Required Default Description

message

string

yes

The message to log.

Exceptions

badRequest

If job isn’t valid any more or message is invalid.

notFound

If job is not found in the database.

logError(message)

Adds a log to the job with the ERROR level.

Parameters

Name Type Required Default Description

message

string

yes

The message to log.

Exceptions

badRequest

If job isn’t valid any more or message is invalid.

notFound

If job is not found in the database.

sys.jobs.JobLog

Contains information about a line of log.

timestamp()

Returns the date in which log has been recorded.

Returns

Date - The date in which log has been recorded

level()

Returns the level of the log. It could be INFO or ERROR.

Returns

string - The level of the log.

message()

Returns the message of the log.

Returns

string - The message of the log

additionalInfo()

Returns additional information of the log. This is specific for the log and the information can vary. Use it only to get more information to diagnose problems, but don’t base your code on information here.

Returns

object - An object with additional info. Could be null.

Back to top