Search code examples
scalacallbackakkascheduler

Akka scheduleOnce callback never called


I have a simple problem/bug, but I can't figure out what's happining. I want to use the ActorSystem scheuler to schedule a callback. The sample code is as follows:

implicit val system: ActorSystem = ActorSystem("system-test1")

system.scheduler.scheduleOnce(2 seconds)(() =>
                                         {
                                           println("Hi")
                                         })

However, nothing is printed to the console and although I have a debugger breakpoint in the println line, the debugger doesn't stop there. Can anyone help me?


Solution

  • system.scheduler.scheduleOnce(2 seconds)(() => { println("Hi") })
    

    The above passes to the scheduleOnce method a function that takes zero arguments and returns Unit. The version of the scheduleOnce method that you're invoking doesn't take a function as a parameter; it takes a call-by-name parameter that is a Unit:

    final def scheduleOnce(delay: FiniteDuration)(f: => Unit)(implicit executor: ExecutionContext): Cancellable  
    

    Therefore, simply pass in println("Hi"), which returns Unit:

    system.scheduler.scheduleOnce(2 seconds)(println("Hi"))