node-cron-trigger
v1.0.19
Published
A Node cron wrapper to run your tasks even if their running time is gone
Downloads
49
Maintainers
Readme
Node-Cron-Trigger
- A Node cron wrapper to run your tasks even if their running time is gone
Installation
Using npm:
$ npm i node-cron-trigger
Using yarn:
$ yarn add node-cron-trigger
Summary
Node-Cron
is a perfect option to schedule tasks on server side to run in a specific time of the day but what if your task is should run at12.00 AM
and the server stopped at11.59 PM
and starts again at12.01 AM
that's mean your cron task won't run again untill the next day so here we need a solution to handle those expaired tasks at any app that's whatNode-Cron-Trigger
does it will combinenode-cron
withnode-parser
to save your tasks data in a file calledhistory.log
that will save your cron tasks by names in object and each key consist of object that have 2 keyscreatedAt
andnextRunDate
so whenever the server restart it will check for the tasks that need to get run if their nextRunDate is passed or not and if they are is passed then it will run them and update it'snextRunDate
property that will happens just with expaired tasks but if the task run without any problems it's will never do anything it will just update that tasknextRunDate
property and keep going that's the process and let's go in details
Usage
Node-Cron-Trigger
lets you define the tasks as an object of keys - the key =the task name
and the value is an object with 3 options- schedule: the cron expression like
* * * * * *
- options:
node-cron
schedule options you can find it in the following url Schedule Options - task: your task handler
- schedule: the cron expression like
NodeCronTrigger
accepts 2 arguments first one start as descriped above and optionaloptions
argument which is an object that object allows you to specify your custom store instead of default filesystem store or the filesystem history.log file path, name likenew NodeCronTrigger({ historyFilePath: process.cwd(), historyFileName: 'tasks.log' })
ornew NodeCronTrigger({ store: new MyCustomStore() })
Options
logging
boolean, default is true (allows you to disable logging)store
: IStore, default is FileStore instance allows you to provide your own store to use it instead of default FileStorehistoryFilePath
: path to the history, this field is required when you are not providing a store it will require you to provide a path to the history filehistoryFileName
: allows you to change the history file name fromhistory.log
to any name you wantUsage example ESM
import { NodeCronTrigger, ITaskOptions, ITaskOptionsList } from "node-cron-trigger";
const options: ITaskOptionsList = {
historyFilePath: __dirname,
logging: true,
};
const tasks: ITaskOptions = {
"runAt12AM": {
schedule: '0 0 0 * * *',
options: {
scheduled: true,
},
task() {
console.log('hey whatever you did i will run at 12 AM even after restarting the server');
},
},
"runEach1Mins": {
schedule: '*/1 * * * *',
task() {
console.log('hey whatever you did i will run each 1 minutes of any hour even after restarting the server');
},
},
};
const runner = new NodeCronTrigger(tasks);
// get list of { tasks, scheduledTasks, cronTasks }
console.log(runner.getJobs());
// get the tasks history object
console.log(runner.getHistory());
// Error: Invalid expression
console.log(runner.validate('* 4'));
// get history file path
console.log(runner.historyPath);
setTimeout(() => {
console.log(runner.Tasks);
runner.store.getItem('history').then(history => console.log(JSON.parse(history), '............ history ..............'));
}, 1000 * 2);
- Usage example CJS
const { NodeCronTrigger } = require('node-cron-trigger');
new NodeCronTrigger(
{
runEach1Mins: {
schedule: '*/1 * * * *',
task() {
console.log(
'hey whatever you did i will run each 1 minutes of any hour even after restarting the server'
);
}
}
},
{
historyFilePath: __dirname,
logging: false
}
);
Store
- storing data by
Node-Cron-Trigger
can made by any data store like databases or redis store or anything else by default it's usingFileStore
to store the history in log file but also you have the free to use your favorite data store but keep in mind that any data store is should provide 3 methodssetItem
which take the data as key, value likelocalStorage
in browser +getItem
which take the key as argument +removeItem
which also takekey
as an argument and each one of them is should return a promise to handle any type of data storage you can checkout the example you can show it inStore.ts
file - in that store all data will be save as json string in key called
history
so if you planning to store history in a pre defined store like SQL you will need to define thehistory
key as a string type likenvarchar(max)
Methods
because of
node-cron-trigger
is a cron wrapper you can use anynode-cron
method and options beside thenode-cron-trigger
default usage described above you can also use a method likeschedule
,validate
,getTasks
ofnode-cron
check node-cron docsAlso 4 more options like
getHistory
which return your tasks object that referred here you can use it likenew NodeCronTrigger(tasks).getHistory()
getTaskNextRunTime
that's will take the cron expression as argument and it will return the date of the task next run date it's just a funny method to checkout your cron expression next run date you can try it likeconsole.log(new NodeCronTrigger(tasks).getTaskNextRunTime('*/5 * * * *'))
clearHistory
that will remove thenode-cron-trigger
history - it's a cleanup method that can be used when you change you cron tasks because ofnode-cron-trigger
will persist any defined tasks even if they removed their data will still exists for example if you was have 3 tasks likerunEach1Mins, runEach2Mins, runEach3Mins
and removed the task ofrunEach1Mins
from your object innode-cron-trigger
the data ofrunEach1Mins
will stay exists so you can use it to remove the old tasks data and it will automatically create a new history with presented cron jobsthat method won't effect any of your tasks whatever the tasks data exists or removed because only defined tasks will run
History
Node-Cron-Trigger
history by default it's a log file that consist of object with one keyhistory
which is a json string contains the data for your tasks - the tasks is saved in the json data as an object liketasks-names
and eachtask-name
is an object with 2 keyscreatedAt
andnextRunDate
the file will looks like
{
"runAt12AM": {
"createdAt": "2024-03-12T02:49:23.536Z",
"nextRunDate": "2024-03-12T22:00:00.000Z"
},
"runEach1Mins": {
"createdAt": "2024-03-12T02:49:23.563Z",
"nextRunDate": "2024-03-12T02:53:00.000Z"
}
}