node-cron-trigger
v1.0.19
Published
A Node cron wrapper to run your tasks even if their running time is gone
Downloads
47
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-triggerUsing yarn:
$ yarn add node-cron-triggerSummary
Node-Cronis 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 AMand the server stopped at11.59 PMand starts again at12.01 AMthat'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-Triggerdoes it will combinenode-cronwithnode-parserto save your tasks data in a file calledhistory.logthat will save your cron tasks by names in object and each key consist of object that have 2 keyscreatedAtandnextRunDateso 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'snextRunDateproperty 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 tasknextRunDateproperty and keep going that's the process and let's go in details
Usage
Node-Cron-Triggerlets you define the tasks as an object of keys - the key =the task nameand the value is an object with 3 options- schedule: the cron expression like
* * * * * * - options:
node-cronschedule options you can find it in the following url Schedule Options - task: your task handler
- schedule: the cron expression like
NodeCronTriggeraccepts 2 arguments first one start as descriped above and optionaloptionsargument 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
loggingboolean, 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.logto 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-Triggercan made by any data store like databases or redis store or anything else by default it's usingFileStoreto 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 methodssetItemwhich take the data as key, value likelocalStoragein browser +getItemwhich take the key as argument +removeItemwhich also takekeyas 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.tsfile - in that store all data will be save as json string in key called
historyso if you planning to store history in a pre defined store like SQL you will need to define thehistorykey as a string type likenvarchar(max)
Methods
because of
node-cron-triggeris a cron wrapper you can use anynode-cronmethod and options beside thenode-cron-triggerdefault usage described above you can also use a method likeschedule,validate,getTasksofnode-croncheck node-cron docsAlso 4 more options like
getHistorywhich return your tasks object that referred here you can use it likenew NodeCronTrigger(tasks).getHistory()getTaskNextRunTimethat'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 * * * *'))clearHistorythat will remove thenode-cron-triggerhistory - it's a cleanup method that can be used when you change you cron tasks because ofnode-cron-triggerwill persist any defined tasks even if they removed their data will still exists for example if you was have 3 tasks likerunEach1Mins, runEach2Mins, runEach3Minsand removed the task ofrunEach1Minsfrom your object innode-cron-triggerthe data ofrunEach1Minswill 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-Triggerhistory by default it's a log file that consist of object with one keyhistorywhich is a json string contains the data for your tasks - the tasks is saved in the json data as an object liketasks-namesand eachtask-nameis an object with 2 keyscreatedAtandnextRunDatethe 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"
}
}