I need an actor to send a message every minute. How do I best achieve this behaviour? I am afraid of using java.lang.Thread.sleep(long millis) as a thread can b
Since scala.actors is now deprecated and being replaced with akka actors (and since there is no react or receiveWithin in akka actors), here is how to do it using akka actors (it's actually less of a 'hack' than using receiveWithin anyways IMHO).
The example below schedule a runnable to be invoked after 5 seconds:
import akka.actor.{ActorSystem, Scheduler}
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.ExecutionContext.Implicits.global
class TimerExample {
def example() = {
def scheduler: Scheduler = ActorSystem.create("timer-example").scheduler
val myRunnable = new Runnable {
override def run(): Unit = {
println("run invoked")
}
}
println("scheduling...")
scheduler.scheduleOnce(FiniteDuration(5,TimeUnit.SECONDS),myRunnable)
Thread.sleep(6000)
println("should have printed 'run invoked'")
}