tags:

views:

61

answers:

2

How do I do the following in groovy:

while (somethingIsntReady || now.isAfter(before + 5 minutes)) {
    sleep(1000)
}

Right now I do something like this:

i = 1
while (!finishedFile.exists() && i in 1..300) {
    sleep(1000)
    i++
}

which doesn't seem right in groovy because it's just the way I would do it in java.

+2  A: 

You can use the TimeCategory for these kind of date expressions. Here's an example together with an additional existsUntil method, that has been added to the File class:

import groovy.time.*

File.metaClass.existsUntil { timeout ->
    boolean result;

    while (!(result = delegate.exists()) && new Date().before(timeout)) {
        sleep(1000)
    }

    return result
}

use( TimeCategory ) {
    finishedFile.existsUntil(30.seconds.from.now)
}
Christoph Metzendorf
Nice use of `from.now` :) I always forget that bit...
tim_yates
perfect, thanks
Gaurav
A: 

Something like this?

def complete = false
use( groovy.time.TimeCategory ) {
  def end = new Date() + 5.seconds
  while( !complete && new Date() < end ) {
    sleep( 1000 )
  }
}
tim_yates