1
\$\begingroup\$

What do you think about this implementation?

inline fun every(duration: Long, timeUnit: TimeUnit, whileCondition: () -> Boolean = { true }, function: () -> Unit) {
 while (whileCondition()) {
 function()
 Thread.sleep(timeUnit.toMillis(duration))
 }
}

This allows calling the following statement:

every(5, TimeUnit.SECONDS){
 println("Hello world")
}
asked Jan 10, 2018 at 9:17
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Usually it's a bad idea to put to sleep whole thread. I'd recommend use Java Timer or kotlin's wrapper for it.

Here is an example:

fixedRateTimer("default", false, 0L, 1000){
 println("Hello!")
 if (theEndIsNear) cancel()
}
answered Jan 15, 2018 at 13:01
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.