bunkat / later

A javascript library for defining recurring schedules and calculating future (or past) occurrences for them. Includes support for using English phrases and Cron schedules. Works in Node and in the browser.
http://bunkat.github.io/later/
MIT License
2.42k stars 244 forks source link

Implementing task runner. #113

Open akulo opened 9 years ago

akulo commented 9 years ago

I am trying to understand how to use later.js to implement following idea. I have requirement where each task has two properties, start time and end time. So I have to run a function at start time and run another function at end time. The end function is only applicable if start time has been executed. Essentially it is start function 1 and after certain duration execute function 2. Any suggestions how it can be accomplished with later.js?

akulo commented 9 years ago

currently I have following code when I want to open and close relay every 2 secs. But I am not sure if its the most elegant way of doing it..

var textSched = later.parse.text('every 4 sec');
var openRelay = function(){
    relay.open();
    var textSched2 = later.parse.text('every 2 sec');
    var timer = later.setTimeout(function(){
        relay.close();
    }, textSched2);
}
var timer2 = later.setInterval(openRelay, textSched);
balmasi commented 8 years ago

From your description, I think this is what you're looking for. For this simple use case I don't think you even need later:

var schedule1 = 4 * 1000,  // Every 4 seconds
    schedule2 = 2 * 1000; // Every 2 seconds

setInterval(openRelay, schedule1);

function openRelay (){
    relay.open();
    var timer = setTimeout(closeRelay, schedul2);
    if (someThingWentWrong) {
      clearTimeout(timer);
    }
}

function closeRelay(){
  relay.close();
}

Is that right?