repeat-job
v1.0.0
Published
Simple util to create and run repeated job
Downloads
3
Readme
repeat-job
This is simple util to run a job repeatedly.
Install
npm install repeat-job
Usage
const RepeatJob = require('repeat-job');
// Create job
const myRepeatJob = new RepeatJob({
job: function () {
console.log(`Current time: ${new Date()}`);
},
delay: 1000});
// `job` function can be `async`
const myRepeatJob = new RepeatJob({
job: async () => {
console.log(`Current time: ${new Date()}`);
},
delay: 1000});
// Start job
myRepeatJob.start();
// Stop job
myRepeatJob.stop();
Required parameters
job
:function(cancelToken)
This is your job, can be async
. This function accepts optional param cancelToken
help you to know when a cancellation is requested.
CancelToken = {
isCancelRequested: Boolean
}
delay
: delay (ms) between job iterations
Example using CancelToken
Use CancelToken
to cancel long running task.
// Use `delay` lib for demonstration
const delay = require('delay');
// Create job with async
const myRepeatJob = new RepeatJob({
job: async (cancelToken) => {
console.log('Begin');
// Simulate long running job
await delay(1000);
if (cancelToken.isCancelRequested) {
console.log('Canceled');
} else {
// Simulate long running job
await delay(1000);
console.log('End');
}
},
delay: 1000});
// Declare CancelToken
const cancelToken = { isCancelRequested : false };
// Start repeat job, passing CancelToken
myRepeatJob.start(cancelToken);
// Use CancelToken to cancel task
setTimeout(() => {
cancelToken.isCancelRequested = true;
}, 500);