I'd like to know if there are any mechanism in Akka that can have an actor executed periodically?
An actor can stop itself by returning. Behaviors. stopped as the next behavior. A child actor can be forced to stop after it finishes processing its current message by using the stop method of the ActorContext from the parent actor.
Behind the scenes Akka will run sets of actors on sets of real threads, where typically many actors share one thread, and subsequent invocations of one actor may end up being processed on different threads.
1) preStart() This is overridable method, so you can override preStart() method to provide specific implementation for an Actor. It is invoked right after the starting of Actor and when an Actor is first created.
In Akka, you can stop Actors by invoking the stop() method of either ActorContext or ActorSystem class. ActorContext is used to stop child actor and ActorSystem is used to stop top level Actor.
You don't really need an actor to do this in Akka 1.3.1 you can schedule a function to be called every 5 minutes like this:
Scheduler.schedule(() => println("Do something"), 0L, 5L, TimeUnit.MINUTES)
However, if you do want it to be an actor for other reasons you would call it like this
case class Message() val actor = actorOf(new Actor { def receive = { case Message() => println("Do something in actor") } }).start() Scheduler.schedule(actor, Message(), 0L, 5L, TimeUnit.MINUTES)
If you're using Akka 2.0 then it would be done like this
val system = ActorSystem("MySystem") system.scheduler.schedule(0 seconds, 5 minutes)(println("do something"))
Or send a message to an actor every 5 minutes like this
case class Message() class MyActor extends Actor { def receive = { case Message() => println("Do something in actor") } } val system = ActorSystem("MySystem") val actor = system.actorOf(Props(new MyActor), name = "actor") system.scheduler.schedule(0 seconds, 5 minutes, actor, Message())
The approach using schedule is one good approach, although there is a potential for the messages to queue up if the work done on schedule is so great that it might take longer than the scheduled interval. If you want the interval to occur between the end of one iteration and the beginning of the next, then use scheduleOnce
with the following pattern:
import akka.actor.Actor import scala.concurrent.duration._ class SchedulingActor extends Actor { override def preStart(): Unit = { self ! "Do Some Work" } def receive = { case "Do Some Work" => doWork context.system.scheduler.scheduleOnce(5 minutes, self, "Do Some Work") } def doWork = ??? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With