How to wait for N seconds between statements in Scala?

ScalaSleep

Scala Problem Overview


I have two statements like this:

val a = 1
val b = 2

In between the 2 statements, I want to pause for N seconds like I can in bash with sleep command.

Scala Solutions


Solution 1 - Scala

You can try:

val a = 1 
Thread.sleep(1000) // wait for 1000 millisecond
val b = 2

You can change 1000 to other values to accommodate to your needs.

Solution 2 - Scala

Given:

package object wrap {
  import java.time._

  def delayed[A](a: => A): A = {
    Console println Instant.now
    Thread.sleep(1000L)
    val x = a
    Console println Instant.now
    x
  }
}

You can:

Welcome to Scala 2.12.0-M3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_60).
Type in expressions for evaluation. Or try :help.

scala> $intp.setExecutionWrapper("wrap.delayed")

scala> { println("running"); 42 }
2016-02-20T06:28:17.372Z
running
2016-02-20T06:28:18.388Z
res1: Int = 42

scala> :quit

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMamunView Question on Stackoverflow
Solution 1 - ScalaCarson PunView Answer on Stackoverflow
Solution 2 - Scalasom-snyttView Answer on Stackoverflow