Search code examples
akkaakka-stream

Full featured Cron scheduling of akka streams


In akka streams it is possible to do the following:

Source.tick(0.seconds, 15.seconds, "Hello")

And your stream will receive tick element "Hello" every 15 seconds. What I'm looking for is the possibility to do the same, but on cron-like schedule e.g. "every monday at 5 pm".


Solution

  • I figured it out. There is an akka plugin akka-quartz-scheduler which allow configuring some quartz schedule configuration like this: Add this section into akka.conf

    akka {
      quartz.schedules {
        SomeSchedule {
          expression = "0 0 1 * * ?"
          timezone = "GMT-7"
          description = "Do something every day at 1 a.m. SF time."
        }
      }
    }
    

    Then schedule it

        case class Signal(someData: String)
    
        implicit val system: ActorSystem = ActorSystem("lebulbeaux-system")
        implicit val materializer: ActorMaterializer = ActorMaterializer()
        // needed for the future flatMap/onComplete in the end
        implicit val executionContext: ExecutionContextExecutor = system.dispatcher
    
        val source: Source[Signal, ActorRef] = Source.actorRef[Signal](100, OverflowStrategy.fail)
    
        val ref: ActorRef = Flow[Signal].to(Sink.foreach(signal => println(signal.someData))).runWith(source)
    
        import com.typesafe.akka.extension.quartz.QuartzSchedulerExtension
    
        QuartzSchedulerExtension(system).schedule("SomeSchedule", ref, Signal("Hello!"))
    
        // scroll
    

    And now you'll receive a signal message every day at 1 a.m. SF time.

    Also, take a look at this issue for more options of using Source.actorRef