I need to call a function every given period of time on a route for example my function:
function hello(){
console.log("Hi")
}
app.post("/", (req,res) => {
res.send("Hi")
hello()
}
Well, I didn't put all the code in my application, just the part that matters, I need to call the hello function every 5 seconds. I need to use this method of calling a given function every given period, in my application.
you can use node-schedule !
for example: Execute a cron job every 5 Minutes = */5 * * * *
var schedule = require('node-schedule');
var j = schedule.scheduleJob('*/5 * * * *', function(){
console.log('The answer to life, the universe, and everything!');
});
Another solution:
setInterval
setInterval(() => {
// do something every 5 seconds
}, 5000);
Related
I want to develop an app which needs to run a scheduled job which writes something to database for every 15 minutes from 9 am to 9 pm
How can i implement this?
Thanks
Look into this package: https://www.npmjs.com/package/node-cron
Here's an example from their docs:
var cron = require('node-cron');
cron.schedule('*/2 * * * *', () => {
console.log('running a task every two minutes');
});
To write to the database the details vary based on what database you're using exactly. For simplicity you can use Express to connect + write to a DB quickly.
Read more here: https://expressjs.com/en/guide/database-integration.html
You can do this.
const CronJob = require("cron").CronJob;
console.log("Before job instantiation");
const job = new CronJob("0 */15 9-21 * * *", function () {
const d = new Date();
console.log("Every 15 minutes between 9-21:", d);
});
console.log("After job instantiation");
job.start();
How can I execute this with different timings? Please help on this. Thanks in Advance...
const Cron = require('node-cron');
const Cron2 = require('node-cron');
var TaskOne = Cron.schedule('*/10 * * * *', async() => {
//first job implemented here and its working fine
function1();
});
var TaskTwo = Cron2.schedule('*/11 * * * *', async() => {
// Second job implemented here....
//Why this block is not getting executed???????????????????????
function2();
});
How can I execute this with different timings? TaskTwo is not getting executed. Debugger not goes into TaskTwo. Please help on this. Thanks in Advance...
if node-cron is not the only prefrence for you then you can use https://github.com/agenda/agenda
There's no need to require the same package twice, so you should remove Cron2 on the second line. Thus the line var TaskTwo = Cron2.schedule('*/11 * * * *', async() => { should be changed to:
var TaskTwo = Cron.schedule('*/11 * * * *', async() => {
As for why the second schedule is not working, it might be because you didn't start() the schedule, as shown in https://github.com/node-cron/node-cron#start. So adding the code below at the end of your script might trigger both cron to run:
TaskOne.start();
TaskTwo.start();
I am using node-cron to send operational emails (currently searching for new emails that need to be sent every minute).
My function (operationalEmails) looks for mongodb records that have a sent flag = false, sends the email, then changes the sent flag = true.
If an iteration of the cron has a large payload of records to send, it could take more than a minute.
How do I ensure the last iteration of the cron is complete before starting a new one?
//Run every Min
cron.schedule("* * * * *", () => {
operationalEmails();
});
you would need to create a simple lock
const running = false;
function operationalEmails() {
if (running) {
return
}
running = true;
// do stuff
running = false;
}
//Run every Min
cron.schedule("* * * * *", () => {
operationalEmails();
});
I'm using Expressjs
At /routes/index.js i have:
app.group('/test', test => {
const testHandler = new testHandler();
test.get('/test-action', testHandler.testAction.bind(testHandler));
});
At /test/handler.js i have
export class testHandler {
constructor() {
}
/**
* #param req
* #param res
* #param next
* #returns {*}
*/
async testAction(req, res, next) {
// todo code here
}
}
I want to create a cronjob to run that route ( for example localhost:3000/test/test-action ) twice an hour.
With PHP i can do it by * */2 * * * php /path_to_webroot/index.php param1 param2
Is there a similar way to do it with Nodejs?
You can use node-cron. It uses similar syntax as you are using in php.
# min hour mday month wday command
*/15 * * * * some-command
to schedule some-command to run every 15 minutes, node-cron would use a similar syntax to specify the time to run:
'0 */15 * * * *'
Well, you need to define your express routes normally. Then inside your cron function you would make a request to that express route you have defined.
request('http://localhost:3000/test/test-action', function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('im ok')
// console.log(body)
}
})
You can use `request inside your corn job. This way your API will get called every specific time.
I have divided a day on 6 parts and each part of a day has its own interval. My function must run in this intervals.
for example 12:00pm - 15:00pm interval is 10 min, so function must be called every 10 min, but 15:00pm - 20:00pm interval is 2 min so from 15:01pm interval must be changed from 10min to 2min.
Need a suggestion how to build this kind of timer.
I can get intervals from mongoDB or local json file.
I guess I have to check what time is it and get an interval (from mongoDB or json file) for that time, then pass it to setInterval() or Cron job scheduler.
Tryed this way but every time im passing new interval last intervals are still working: If interval is 2 min and im changing it to 5 min, function is called twice: every 2 min and every 5 min in both setInterval() and Cron
const test = (min) => {
console.log(min);
var intervale = setInterval(() => {
console.log('firing', min, new Date());
}, min);
}
const test = (min) => {
cron.schedule(`0 */${min} * * * *`, () => {
console.log('firing cron', new Date())
});
}
thank you
Can you do something like this? This uses the EventEmitter model and fires an event based on the custom Interval.
const eventemitter_cls = require("events").EventEmitter;
let eventemitter = new eventemitter_cls();
intervalName = "randomintervals"
let sumOfTwoNumbers = () => {
console.log(`hello world ${(new Date()).getMinutes()} ${(new Date()).getSeconds()}` );
// After you are done with your function, again you need to emit the event based on the time interval
setTimeout(() => {
eventemitter.emit(intervalName)
}, getTimeInterval());
}
let getTimeInterval = () => {
let currentTime = new Date();
// put your complicated interval schedule here
if(currentTime.getHours() >= 10 && currentTime.getHours() < 11){
return 5000;
}
else if (currentTime.getHours() > 12 && currentTime.getHours() < 15) {
return 2000;
}
else{
return 1000;
}
}
// give your function name here. the function will be called whenever someone emits intervalName
eventemitter.on(intervalName, sumOfTwoNumbers);
eventemitter.emit(intervalName);
I think It's still firing because there is no clearInterval telling it to stop.