简体   繁体   中英

Timer that can be used in JVM Scala & Scala.js

At the moment I am working on a project that is cross-compiled to Scala.js and normal JVM Scala. Now I need to implement a timer (for reconnecting a websocket) that triggers a function every x seconds. What would be a good implementation of such a timer that can be cross compiled?

As far as I know I cannot use eg:

  • java.util.concurrent (doesn't compile to Scala.js)
  • setTimeout and setInterval (javascript - not usable from JVM Scala)

Is there any good alternative or am I wrong and these can be used?

java.util.Timer is supported by Scala.js, and provides exactly the functionality you're describing:

val x: Long = seconds
val timer = new java.util.Timer()
timer.scheduleAtFixedRate(new java.util.TimerTask {
  def run(): Unit = {
    // this will be executed every x seconds
  }
}, 0L, x * 1000L)

Consult the JavaDoc that I linked above for details about the API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM