We’re currently working on a Service Fabric project where we have to implement a Service Fabric Actor that does work, based on a certain schedule or timeframe.
One of the challenges in this implementation was activating the actor immediately after deployment and registration.
This blogpost will explain on how this problem was handled.
If you are not familiar with Service Fabric Actors, please have a look at this in-depth description of the Actor Design Pattern and Service Fabric Reliable Actors: https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-actors-introduction/
Timers vs Reminders
Service Fabric Actors can schedule periodic work by registering either timers or reminders.
The main difference between timers and reminders is that reminders are triggered under all circumstances, until the actor unregisters the reminder or the actor is explicitly deleted.
Specifically, reminders are triggered across actor deactivations and failovers, because the Actors runtime persists information about the actor’s reminders.
In-depth details of timers and reminders can be found here: https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-actors-timers-reminders/
How did we do it?
The implementation starts with creating a Reliable Actor. When the Actor is being activated we register a reminder to do a certain job every 30 seconds. The actual job is being implemented in the ReceiveReminderAsync method.
In our case, the StartWork method is simply there to trigger the activation of the Actor. The activation of the actor is done inside an ActorService. This service is a simple derived service from the base ActorService.
The only difference here is that inside the run we create and active an instance of our ISchedulingActor and that way start the 30 seconds reminder.
The only thing we then have to change is the entry point of the service host process. In the main method instead of using the base ActorService to register our Actor.
We are using our own derived service SchedulingActorService to register the Actor and that way trigger the RunAsync (and therefor the creation and activation of our actor) on the SchedulingActorService.
Timers and reminders are a great way to schedule periodic work for your Service Fabric Actors. For our specific implementation it was important that the Service Fabric Actor was activated immediately after deployment.
Using the above implementation of creating a derived service based on the Actor Service is a good approach to achieve that goal with a small amount of effort in a ‘static’ Actor Scenario.
Keep in mind that the reminder or timer is re-initialized every time the primary replica of your actor service is started. This happens after failover, resource balancing, upgrade,… So make sure that your methods and actions performed by your Reliable Actor are idempotent.