addTaskRunFailedListener
The addTaskRunFailedListener
method registers a listener function with the Manager
that will be called whenever a task run fails, whether because of timeout, error, or deletion.
addTaskRunFailedListener(
taskId: IdOrNull,
taskRunId: IdOrNull,
listener: TaskRunFailedListener,
): string
Type | Description | |
---|---|---|
taskId | IdOrNull | The |
taskRunId | IdOrNull | The |
listener | TaskRunFailedListener | The function that will be called whenever a matching task run has failed. |
returns | string | A unique |
The provided listener is a TaskRunFailedListener
function, and will be called with a reference to the Manager
, the Id
of the task, the Id
of the task run that changed, the reason it failed, and a string message (in the case of an error being thrown).
You can either listen for a run of a single task starting (by specifying the task Id
as the method's first parameter) or for a run of any task starting (by providing a null
wildcard). You can specify a specific task run Id
to listen for with the second parameter, or null
to listen for any matching task run starting.
Examples
This example registers a listener that responds to failures of any run of the 'ping' task.
import {createManager} from 'tinytick';
const manager = createManager().start();
manager.setTask('ping', async () => {
throw new Error('Network error');
});
const listenerId = manager.addTaskRunFailedListener(
'ping',
null,
(manager, taskId, taskRunId, reason, message) =>
console.log(
`Task '${taskId}' failed with reason: ${reason}, ${message}`,
),
);
manager.scheduleTaskRun('ping');
// ... wait 100ms for task to start and fail
// -> "Task 'ping' failed with reason: 4, Network error"
manager.delListener(listenerId);
This example registers a listener that responds to the inevitable timeouts of the 'takesTwoSeconds' task run.
import {createManager} from 'tinytick';
const manager = createManager().start();
manager.setTask(
'takesTwoSeconds',
async () => await new Promise((resolve) => setTimeout(resolve, 2000)),
undefined,
{maxDuration: 50},
);
const listenerId = manager.addTaskRunFailedListener(
'takesTwoSeconds',
null,
(manager, taskId, taskRunId, reason) =>
console.log(`Task '${taskId}' timed out (reason: ${reason})`),
);
manager.scheduleTaskRun('takesTwoSeconds');
// ... wait 250ms for task to start and time out
// -> "Task 'takesTwoSeconds' timed out (reason: 3)",
manager.delListener(listenerId);
Since
v1.2.0