Skip to content

Example: DelayQueue for Scheduled Task Management

Monmohan edited this page Dec 17, 2013 · 1 revision
(function () {
    var DelayQueue=require('dsjslib').DelayQueue;    
    //create some tasks
    var schTask1 = {
        /*will happen in 30 seconds*/
        'schedule' : Date.now() + 30 * 1000,
        'name' : 'pick milk',
        'handler' : function () {
            //do something with task here
            console.log(this.name);
        }
    };

    var schTask2 = {
        /*will happen in one minute*/
        'schedule' : Date.now() + 60 * 1000,
        'name' : 'dance',
        'handler' : function () {
            //do something with task here
            console.log(this.name);
        }
    };

    //and some more tasks ..

    var taskDelayFn = function (task) {
        return task.schedule - Date.now();
    };

    var schTaskQ = new DelayQueue(taskDelayFn);

    schTaskQ.offer(schTask1).offer(schTask2);

    //and more tasks can be added any time to the Queue

    //see if we need to do something

    schTaskQ.take(/*my task callback*/
        function (err,task) {
            task.handler();
        });

}());
Clone this wiki locally