node-cron / node-cron

A simple cron-like job scheduler for Node.js
ISC License
2.98k stars 255 forks source link

90 second scheduling #316

Open Vivi029 opened 2 years ago

Vivi029 commented 2 years ago

Hello, I need help with this library, as the title says I need to schedule something on in weird ways (every 1 minute and 20 seconds, every 4 hours and 10 minutes). I did some digging online and find some solutions for this, one of them is using multiple cron for the same task. I've tried implementing it, but it's not really working out, especially since I have to schedule according to timestamps received from another server. I've come up with a way to convert the timestamps into a cron pattern but when it comes odd timestamps such as 90 (1 minute and 30 seconds) it gets messy. The other option was to use fcron which supposedly supports these odd tasks but I couldn't find any node js implementation of it. So is there anyway I could use cron without having to use two crons, and if impossible how would I go about updating this algorithm for it to support that. Here is the algorithm I've come up with:

secondsToCronTime(time){
    let stringToReturn = "";
    if(time <= 59){
        stringToReturn = '*/${time} * * * * *';
    } else if (time >= 60 && time < 3600){
        let residue = time % 60;
        let timeleft = (time - residue) / 60;
        stringToReturn = '${residue != 0 ? residue: '0'} */${timeleft} * * * *';
   } else if (time >= 3600 && time < 84400){
        let secResidue = time % 60;
        let minutesLeft = (time - secResidue) / 60;
        let minResidue = minutesLeft % 60;
        let hoursLeft = (minutesLeft - minResidue) / 60;
        stringToReturn = '${secResidue != 0 ? secResidue: '0'} ${minResidue != 0 ? minResidue: '0'} */${hoursLeft} * * *';
    }
    return stringToReturn;
}
Hexagon commented 2 years ago

See https://github.com/Hexagon/croner/issues/52#issuecomment-1040764526 for an example on how to solve this using a standard cron module.

This specific example is for months, but could easily be converted to run each 90th second or whatever, while still having the possibility to restrict hours, days etc using standard cron.

I would run each 10th second, and create a secondDiff function that checks for 90 second increments.