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" } )

Run OS command

//windows
String cmd = "ping google.com"

String[] command = ["CMD", "/C", cmd] as String[]
ProcessBuilder builder = new ProcessBuilder(command)
Process process = builder.start()

println process.text

println "*"*5+"DONE"+"*"*5

Sunday, January 6, 2013

String padding with zeros

String.metaClass.zeropad = { Integer padding = 0 ->
    return ("0" * Math.max(0, (padding ?: 0) - delegate.size())) + delegate
}
Integer.metaClass.zeropad = { Integer padding = 0 ->
    return delegate.toString().zeropad(padding)
}

assert "123".zeropad()     == "123"
assert "123".zeropad(null) == "123"
assert "123".zeropad(5)    == "00123"
assert "1234".zeropad(5)   == "01234"
assert "12345".zeropad(5)  == "12345"
assert "123456".zeropad(5) == "123456"

assert 123.zeropad()     == "123"
assert 123.zeropad(null) == "123"
assert 123.zeropad(5)    == "00123"
assert 1234.zeropad(5)   == "01234"
assert 12345.zeropad(5)  == "12345"
assert 123456.zeropad(5) == "123456"