Scheduling Jobs with Akka Scheduler

Hey folks, in this blog I am going to explain how can you schedule jobs that you want to repeat over a certain period of time with the help of Akka Scheduler.

Suppose you have a use-case in which you want some cleaning background process to run a cleanup-repository method to delete records after a fixed interval of time, then look nowhere else because Akka scheduler can provide you with a solution.

The Akka scheduler is not designed for long-term scheduling (see Akka-quartz-scheduler instead for this use case) nor is it to be used for highly precise firing of the events. With Akka scheduler, the maximum amount of time with which we can trigger an event in the future is 8 months.

Let’s understand how can we schedule jobs with the help of an example.

Suppose you have a simple actor like the following:

Now, this actor prints some output on the console when it receives messages.

Suppose you want to send a message after every 50 milliseconds to this Actor.

With the help of Akka-Scheduler, you can automate this process by using a scheduler that sends messages to this actor after every 50 milliseconds as shown below:

Now here the first parameter in our Akka-Scheduler is the initial delay, in this case, the initial delay is of 0 milliseconds i.e. the scheduler will start scheduling (sending messages to the actor) as soon as the application starts.

The second parameter is the interval after which we want to send the messages, so in this case, we are sending messages to the actor after every 50 milliseconds.

The third parameter is the actorRef i.e. the reference of the actor to which we want to send messages. In this case, simpleJob is the actorRef of SimpleJob actor defined earlier.

The fourth parameter in the message that we want to send to the actorRef after the given interval and the given initial delay.

Now when we will run this application it will print the same message (This actor has received an invalid message) on the console after every 50 milliseconds.

So in this way, we can easily schedule jobs using Akka Scheduler.

Here is the GitHub repository link of the example explained in this blog. You can check out the example and feel free to ask any queries.


References :

Written by 

Manjot Kaur is a software consultant, having more than 0.5 years of experience. She likes to explore new technologies and trends in the IT world. Her hobbies include Travelling, watching movies and running. She is currently working on Technologies like scala with maven, dynamoDb, Akka-Http.

Leave a Reply

%d bloggers like this: