简体   繁体   中英

Dynamic time interval to call a function node.js

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);

我认为它仍在触发,因为没有clearInterval告诉它停止。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM