arrow-down
    1. Widgets
  1. IAM
    1. Virtual apps
    1. Projects
    2. Layers
        1. AttachmentUploader
        2. Checkbox
        3. Combobox
        4. ContentSelector
        5. ContentTypeFilter
        6. CustomSelector
        7. Date
        8. DateTime
        9. Double
        10. GeoPoint
        11. HtmlArea
        12. ImageSelector
        13. Long
        14. MediaSelector
        15. Radiobutton
        16. Tag
        17. TextArea
        18. TextLine
        19. Time
      1. Field set
      2. Item set
      3. Option set
      4. Mixins
      5. Localization
    3. Content Types
    4. X-data
    5. Macros
    6. Custom styles
    7. Sites
      1. Regions
      2. Part component
      3. Layout component
      4. Text component
      5. Fragments
      6. Filtering
      7. Component indexing
      8. Visual editor
    8. Page templates
    1. Sandboxes
    2. Code
    3. Building
    4. Configuration
    1. Globals
    2. HTTP
    3. Controllers
    4. Filters
    5. Events
    6. Websocket
    7. Error handler
    8. ID provider
    9. Tasks
    10. Localization
    11. Mappings
    12. Components
    13. Processors
    14. Contributions
    15. Templating
    16. Main controller
    17. Java bridge
      1. Webapp Engine
        1. Image service
        2. Component service
      2. Admin Engine
      3. Asset service
      4. HTTP service
      5. IDprovider service
    1. Task engine
    2. Management Endpoint
    3. Statistics Endpoint
    1. Nodes and repos
    2. Properties
    3. Indexing
    4. Branches
    5. Queries (NoQL)
    6. Queries (DSL)
    7. Filters
    8. Aggregations
    9. Highlighting
    10. Editors
    1. Strategies
    2. Distributions
    3. Docker image
    4. Vhosts
    5. Configuration
    6. Backup & restore
    7. Systemd
    8. Clustering
    1. Admin API
    2. Application API
    3. Auditlog API
    4. Authentication API
    5. Cluster API
    6. Common API
    7. Content API
    8. Context API
    9. Event API
    10. Export API
    11. Grid API
    12. I18N API
    13. IO API
    14. Mail API
    15. Node API
    16. Portal API
    17. Project API
    18. Repo API
    19. Scheduler API
    20. Schema API
    21. Tasks API
    22. Value API
    23. VHost API
    24. Websocket API
  2. Audit Logs
    1. Upgrade Notes
    2. Upgrading Apps

Task API

Contents

Functions for execution of asynchronous tasks.

Usage

Add the following to your build.gradle file:

dependencies {
  include "com.enonic.xp:lib-task:${xpVersion}"
}

Add the import statement to your controller:

import taskLib from '/lib/xp/task';

You are now ready to use the API.

Events

Usage of this API produces the following events:

Table 1. Distributed events
Event Occurs when

task.submitted

a task is submitted

task.updated

a task is updated

task.removed

a task is removed

task.finished

a task completes

task.failed

a task fails

For more information on events, check out the event API

Functions

get

Returns the current state and progress details for the specified task.

Parameters

Name Type Description

taskId

string

Id of the task

Returns

object : (TaskInfo) Detail information for the task. Or null if the task could not be found.

Example

Obtains details for an active task:
import {get as getTask} from '/lib/xp/task';

const taskInfo = getTask('7ca603c1-3b88-4009-8f30-46ddbcc4bb19');

if (taskInfo) {
  log.info('Current task state = %s', taskInfo.state);
} else {
  log.info('Task not found');
}
Return value:
const expected = {
  description: "Long running task",
  id: "7ca603c1-3b88-4009-8f30-46ddbcc4bb19",
  name: "task-7ca603c1-3b88-4009-8f30-46ddbcc4bb19",
  state: "RUNNING",
  application: "com.enonic.myapp",
  user: "user:store:me",
  startTime: "2017-10-01T09:00:00Z",
  progress: {
    info: "Processing item 33",
    current: 33,
    total: 42
  }
};

isRunning

Checks if any task with the given name or id is currently running.

Parameters

Name Type Description

task

string

Name or id of the task.

Returns

boolean : true if there is a task with the specified name or id, and state 'RUNNING'; false otherwise.

Example

Check if a task is currently running:
import {isRunning} from '/lib/xp/task';

if (!isRunning('com.enonic.myapp:clean-up-task')) {
  log.info('Start task...');
} else {
  log.info('Task already running');
}

list

Returns the list of running tasks with their current state and progress details. On clustered environments aggregated list is returned.

Parameters

Name Type Attributes Description

params

object

<optional>

JSON with optional parameters

Properties
Name Type Attributes Description

name

string

<optional>

Filter by name

state

object

<optional>

Filter by task state (WAITING | RUNNING | FINISHED | FAILED).

Returns

Array : (TaskInfo[]) List with task information for every task.

Example

1. Obtains list of active tasks:
import {list} from '/lib/xp/task';

const tasks = list();
Return value:
const expected = [
  {
    description: "Long running task",
    id: "7ca603c1-3b88-4009-8f30-46ddbcc4bb19",
    name: "task-7ca603c1-3b88-4009-8f30-46ddbcc4bb19",
    state: "RUNNING",
    application: "com.enonic.app1",
    user: "user:store:user1",
    startTime: "2017-10-01T09:00:00Z",
    progress: {
      info: "Processing item 33",
      current: 33,
      total: 42
    }
  },
  {
    description: "Update statistics",
    id: "b6173bcb-bf54-409b-aa6b-96ae6fcec263",
    name: "task-b6173bcb-bf54-409b-aa6b-96ae6fcec263",
    state: "FINISHED",
    application: "com.enonic.app2",
    user: "user:store:user2",
    startTime: "2017-10-02T09:00:00Z",
    progress: {
      info: "Work completed",
      current: 0,
      total: 0
    }
  },
  {
    description: "Import remote data",
    id: "e1f57280-d672-4cd8-b674-98e26e5b69ae",
    name: "task-e1f57280-d672-4cd8-b674-98e26e5b69ae",
    state: "FAILED",
    application: "com.enonic.app3",
    user: "user:store:user3",
    startTime: "2017-10-03T09:00:00Z",
    progress: {
      info: "Fetching data",
      current: 33,
      total: 100
    }
  }
];
2. Obtains list of running tasks with a given name and state:
import {list} from '/lib/xp/task';

const tasks = list({
  name: "com.enonic.myapp:clean-up",
  state: "RUNNING"
});
Return value:
const expected = [
  {
    description: "Long running task",
    id: "7ca603c1-3b88-4009-8f30-46ddbcc4bb19",
    name: "com.enonic.myapp:clean-up",
    state: "RUNNING",
    application: "com.enonic.myapp",
    user: "user:store:user",
    startTime: "2017-10-01T09:00:00Z",
    progress: {
      info: "Processing item 33",
      current: 33,
      total: 42
    }
  }
];

progress

Reports progress information from an executing task. This function can only be called within the context of a task function, otherwise it will fail and throw an exception.

Parameters

Name Type Description

params

object

JSON with progress details

Properties
Name Type Attributes Description

current

number

<optional>

Integer value representing the number of items that have been processed in the task

total

number

<optional>

Integer value representing the total number of items to process in the task

info

string

<optional>

Text describing the current progress for the task

Returns

void

Example

Execute task and keep taskId for polling status:
import {executeFunction, progress} from '/lib/xp/task';

const taskId = executeFunction({
  description: 'Background task',
  func: () => {

    progress({info: 'Initializing task'});

    for (const i of Array(10).keys()) {
      progress({
        info: 'Processing item ' + (i + 1),
        current: i,
        total: 10
      });

      processItem(i);
    }

    progress({info: 'Task completed'});
  }
});

sleep

Causes the current execution thread to sleep (temporarily cease execution) for the specified number of milliseconds.

Parameters

Name Type Description

timeMillis

number

The length of time to sleep in milliseconds

Returns

void

Example

Execute task and keep taskId for polling status:
import {sleep} from '/lib/xp/task';

let retries = 3;
let result = fetchRemoteData();

while (!result && retries > 0) {
  // wait half a second before retrying
  sleep(500);
  retries -= 1;
  result = fetchRemoteData();
}

executeFunction

Executes a function in the background. Returns an id representing the task of execution.

This function returns immediately. The callback function will be executed asynchronously.

Parameters

Name Type Description

params

object

JSON with the parameters

Properties
Name Type Description

description

string

Text describing the task to be executed

func

function

Callback function to be executed asynchronously

Returns

string : Id of the task function that will be executed.

Example

Execute task function and keep taskId for polling status:
import {executeFunction} from '/lib/xp/task';

const taskId = executeFunction({
  description: 'Background function',
  func: () => {
    longRunningFunction();
  }
});

submitTask

Submits a named task to be executed in the background and returns an id representing the task.

This function returns immediately. The callback function will be executed asynchronously.
lib-task prior version 7.6 does not submit distributable named tasks, instead task always gets executed locally. Recompile your application with the newer library version in order for tasks to be distributable.

Parameters

Name Type Description

params

object

JSON with the parameters

Properties
Name Type Attributes Description

descriptor

string

Descriptor of the task to execute. Descriptor can be relative to the current application, or a fully qualified task descriptor name (<appname>:<taskname>) XP XP 7.13.0 7.13.0

name

string

<optional>

Optional name of the task which appears in task info. If not specified, descriptor name will be used instead.

config

object

<optional>

Configuration parameters to pass to the task to be executed. The object must be valid according to the schema defined in the form of the task descriptor XML.

Returns

string : Id of the task that will be executed.

Example

Execute task, located in the current app, by name:
import {submitTask} from '/lib/xp/task';

const taskId = submitTask({
  descriptor: 'job42',
  config: {
    count: 123
  }
});
Execute a task located in a different app:
import {submitTask} from '/lib/xp/task';

const taskId = submitTask({
  descriptor: 'com.enonic.app.myapp:work',
  config: {}
});

submit

Deprecated from XP XP 7.7.0 7.7.0
Replaced with executeFunction.

submitNamed

Deprecated from XP XP 7.7.0 7.7.0
Replaced with submitTask

Type Definitions

TaskInfo

Type

object

Properties

Name Type Description

id

string

Task Id

name

string

Task name

description

string

Task description

state

string

Task state (WAITING | RUNNING | FINISHED | FAILED)

application

string

Application containing the callback function to run

user

string

Key of the user that submitted the task

startTime

string

Time when the task was submitted (in ISO-8601 format)

progress

object

Progress information provided by the running task

node

string

XP cluster node the task is running on XP XP 7.13.0 7.13.0

Properties
Name Type Description

current

number

Integer value representing the number of items that have been processed in the task

total

number

Integer value representing the total number of items to process in the task

info

string

Text describing the current progress for the task


Contents

Contents

AI-powered search

Juke AI