Reputation: 33
I want to create a periodic Poller which polls every x milliseconds something.
I want to start and stop it via URL
val pollingActor = actor {
var loop = true
loopWhile(loop) {
react {
case "Stop" => {
Console.println("Poller Stopping")
loop = false
exit
}
case "Start" => {
Console.println("Poller Starting")
loop = true
}
}
pollMyResults() // this is my poller
}
}
but, this doesn#t work , the actor just gets called once, when i the start the poller with
pollingActor ! "start"
What am i doing wrong ? did i missunderstand the loop in the actor ?
Upvotes: 0
Views: 753
Reputation: 8932
You can use Akka scheduler
Akka.system.scheduler.schedule(1 seconds, interval, tracker, Tick)
See here for a working example in a pet from me.
Upvotes: 1
Reputation: 35463
I would start by switching your actor over to Akka. Play is already built on top of Akka and the scala actor API has been deprecated and will be removed soon. Then, you can leverage the Akka ActorSystem
Scheduler
to handle the scheduling aspect and let the actor itself only handle the polling. The refactored actor could look like this:
import akka.actor._
class PollingActor extends Actor{
def receive = {
case "poll" =>
//do polling work here
}
}
Then schedule it's execution outside of the actor. All you need is a reference to the ActorSystem
that play is running on top of:
import scala.concurrent.duration._
val poller = system.actorOf(Props[PollingActor], "poller")
val cancellable = system.scheduler.schedule(0 milliseconds, 100 milliseconds, poller, "poll")
In this example, the poller
will be sent a "poll"
message every 100 milliseconds. If you wanted to stop polling, then you can just call cancel
on the cancellable
reference returned from the call to schedule
.
Upvotes: 1