Monday, January 7, 2013

Simple Timer & TimerTask

public class MyTask extends TimerTask{
    Closure onFinish
    int count, repeat
    
    public MyTask(Closure onFinish = {}, int repeat = 1){
        this.onFinish = onFinish
        this.repeat = repeat
        this.count = 1
    }
    
    private void toDo(){
        println "count-> ${count}"      
    }
    
    private void checkFinished() {
        if (count > repeat) { //this is the condition when you want to stop the task.
            println "DONE-> before ${count}"
            onFinish()
            return
        }
    }
    
    @Override
    public void run() {        
        toDo()
        count++
        checkFinished()
    }
}

public class MyScheduler {
    public static void doIt( Closure then = {} ) {
        Timer timer = new Timer()
        MyTask myTask = new MyTask( repeat:3, 
            onFinish:{ 
                timer.cancel() // stop the timer
                then() // do the callback
            })
        int delayStartMs = 2000
        int intervalMs = 1000
        timer.schedule(myTask, delayStartMs, intervalMs)
    }
}

MyScheduler.doIt( { println "#1 DONE" } )
MyScheduler.doIt( { println "#2 DONE" } )

No comments:

Post a Comment