The tasks plugin is used to register functionality to be executed at specific points in time, recurring or not. This plugin is useful for a worker-like microservice that can process items in the background.
By default, the plugin will create the folder app/tasks where you should save all your task definitions. They will be automatically loaded and registered by the application.
npm i --save thorin-plugin-tasks@1.x
'use strict'; // app.js entry file const thorin = require('thorin'); thorin.addPlugin(require('thorin-plugin-tasks')); // <- add this line thorin.run((err) => {});
#update config/app.js with your configuration
# run to setup the plugin node app.js --setup=plugin.tasks
TaskEntry
classYou use the task entry to define what and when gets executed.
hh:mm:ss
format or {days}d {hours}h {minutes}m {seconds}s
and can be found below:delay: '2m'
delays next execution by 2 minutestimer: '10s'
executes the task every 10 secondsat: '10:30'
executes the task every day at 10:30timer: '2h30m'
executes the task every 2 hours and 10 minutes
failed
- triggered when the task has encountered an error.
completed
- triggered when the task has completed all its scheduled actions.
timeout
- triggered when the action failed to complete before the given timeout period
stop
- triggered when the action was programatically stopped from the context.
TaskContext
classYou use the task context to attach context-specific information about your currently running task.
'use strict';
const taskPlugin = thorin.plugin('tasks');
const myTask = taskPlugin.addTask('my.task.right.here');
myTask
.prepare((context) => {
// Set any context information.
context.items = [];
context.processed = 0;
})
.action('dequeue', (context) => { // Return a promise to signal the action completion.
return new Promise((resolve, reject) => {
log.info('Should dequeue');
context.items.push("myItem");
resolve();
});
})
.action('process', (context) => { // If returns undefined, go to next action automatically.
if(context.items.length === 0) return;
context.items.forEach((item) => {
log.info('Processing item ', item);
context.processed++;
});
})
.action('release', (context) => {
if(context.processed === 0) return;
log.info('Releasing items');
context.items = [];
});
// Schedule the way our actions will be executed and when
myTask.schedule([
'dequeue',
'process',
'release'
], {
delay: '2s',
timer: '40s',
timeout: '30s'
});
// Listen for any events.
myTask
.handle('completed', (context) => {
log.info('Processed: ', context.processed);
})
.handle('failed', (context, err) => {
log.warn(`Failed to finalize task`, err);
});
You can always create a new issue on GitHub or contact one of the core founders by chat.