Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Akka Scheduler: An Alternative to Akka Quartz?

DZone's Guide to

Akka Scheduler: An Alternative to Akka Quartz?

In the Java world, Quartz is somewhat of a standard for scheduling jobs. In this post, though, we take a look at using Akka Scheduler as a possible alternative.

· Java Zone
Free Resource

Learn how our document data model can map directly to how you program your app, and native database features like secondary indexes, geospatial and text search give you full access to your data. Brought to you in partnership with MongoDB.

In this blog, we will be scheduling jobs based on time using Akka Scheduler. The jobs will be scheduled based on IST (Indian Standard Time). It is basically an alternative to Quartz Scheduler to some extent, which is also used to schedule the time-based jobs. We can schedule jobs at any point of time, including scheduling jobs based on IST or any other time zone, say UTC, for example.

Let’s say you want your job to be scheduled at 9:00:00 AM IST every day. What would you do? Scheduling such a job using the normal Akka Scheduler is not easy. So what I have done is
written an extra function so that our normal Akka Scheduler acts as a Quartz Scheduler, but only time-based — not calendar-based. With the example I am going to share, you will be able to schedule time-based jobs for almost any time zone. You just need to mention the which one. In this example, I am focusing on IST (Indian Standard Time) but you can obviously tweak it.

Scheduling Our Example

Let's say our task is to send an email every day at 09:00:00 AM.

Akka Quartz is one way to do it, but if you can play around with the normal Akka Scheduler, why mess around with that?

So, let’s head over to the code and see how can we accomplish it.

Here is the Schedule Actor Class:

import akka.actor.Actor

class ScheduleActor extends Actor {
    import ScheduleActor._
    var count = 1
        //I am using var over here because it's a simple example to increment count. However you should prefer immutability wherever possible.
    def receive: PartialFunction[Any, Unit] = {
        case IncrementNumber => count += 1
        println(count)
    }
}

/**
 * Created by deepak on 22/1/17.
 */
object ScheduleActor {
    case object IncrementNumber
}


And here is the implementation for the job.

import java.text.SimpleDateFormat
import java.util. {
    Date,
    TimeZone
}

import scala.concurrent.duration._

import ScheduleActor.IncrementNumber
import akka.actor. {
    ActorSystem,
    Props
}

/**
 * Created by deepak on 22/1/17.
 */
object ScheduleJob extends App {

    val system = ActorSystem("SchedulerSystem")
    val schedulerActor = system.actorOf(Props(classOf[ScheduleActor]),
        "Actor")
    implicit val ec = system.dispatcher
    system.scheduler
        .schedule(calculateInitialDelay().milliseconds, 60. seconds)(
            schedulerActor!IncrementNumber)
        //the first argument in the schedule function is the initial delay 
        //the second argument in the schedule function is the interval
    def calculateInitialDelay(): Long = {
            val now = new Date()
            val sdf = new SimpleDateFormat("HH:mm:ss")
            sdf.setTimeZone(TimeZone.getTimeZone("IST"))
            val time1 = sdf.format(now)
            val time2 = "00:00:00" //this is where we provide the time(IST)
            for example I want the job scheduled at 9 PM IST I would replace 00: 00: 00
            with 21: 00: 00
            val format = new SimpleDateFormat("HH:mm:ss")
            val date1 = format.parse(time1)
            val date2 = format.parse(time2)
            val timeDifference = date2.getTime() - date1.getTime()
            val calculatedTime =
            if (timeDifference < 0)
                (Constant.DAYHOURS + timeDifference)
            else timeDifference
                // val modifiedDate = projectDbService.getModifiedDate("sumit")
            calculatedTime
        }
        //Calculate initial delay method basically triggers the job at the IST 
    time provided above.
}


That’s all! You are all set to schedule time-based jobs without using Quartz Scheduler.

If you're interested, the full code is available on GitHub. If you find any challenges, let me know in the comments. If you enjoyed this post, I’d be very grateful if you’d help it spread.K eep smiling, keep coding! Cheers!

Discover when your data grows or your application performance demands increase, MongoDB Atlas allows you to scale out your deployment with an automated sharding process that ensures zero application downtime. Brought to you in partnership with MongoDB.

Topics:
scheduler ,jobs ,quartz ,java ,akka ,tutorial

Published at DZone with permission of Deepak Mehra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}