alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Akka/Scala example source code file (SchedulerDocSpec.scala)

This example Akka source code file (SchedulerDocSpec.scala) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Akka and Scala source code examples by using tags.

All credit for the original source code belongs to akka.io; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Akka tags/keywords

actor, akka, akkaspec, anyref, concurrent, do, info, schedulerdocspec, test, testing, tick, tickactor, time

The SchedulerDocSpec.scala Akka example source code

/**
 * Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
 */
package docs.actor

import language.postfixOps

//#imports1
import akka.actor.Actor
import akka.actor.Props
import scala.concurrent.duration._

//#imports1

import org.scalatest.{ BeforeAndAfterAll, WordSpec }
import org.scalatest.Matchers
import akka.testkit._

class SchedulerDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) {
  "schedule a one-off task" in {
    //#schedule-one-off-message
    //Use the system's dispatcher as ExecutionContext
    import system.dispatcher

    //Schedules to send the "foo"-message to the testActor after 50ms
    system.scheduler.scheduleOnce(50 milliseconds, testActor, "foo")
    //#schedule-one-off-message

    expectMsg(1 second, "foo")

    //#schedule-one-off-thunk
    //Schedules a function to be executed (send a message to the testActor) after 50ms
    system.scheduler.scheduleOnce(50 milliseconds) {
      testActor ! System.currentTimeMillis
    }
    //#schedule-one-off-thunk

  }

  "schedule a recurring task" in {
    new AnyRef {
      //#schedule-recurring
      val Tick = "tick"
      class TickActor extends Actor {
        def receive = {
          case Tick => //Do something
        }
      }
      val tickActor = system.actorOf(Props(classOf[TickActor], this))
      //Use system's dispatcher as ExecutionContext
      import system.dispatcher

      //This will schedule to send the Tick-message
      //to the tickActor after 0ms repeating every 50ms
      val cancellable =
        system.scheduler.schedule(0 milliseconds,
          50 milliseconds,
          tickActor,
          Tick)

      //This cancels further Ticks to be sent
      cancellable.cancel()
      //#schedule-recurring
      system.stop(tickActor)
    }
  }
}

Other Akka source code examples

Here is a short list of links related to this Akka SchedulerDocSpec.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.