Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

playframework 2.0 - play framework 2.1 - scheduling async tasks

In play's 2.0.x doc you can see how to schedule asynchronous tasks:

http://www.playframework.org/documentation/2.0.4/ScalaAkka

Akka.system.scheduler.schedule(0 seconds, 30 minutes, testActor, "tick")

How can you achieve the same thing withthe recently releades Play 2.1???

The whole akka API seems to have changed...

I've checked:

https://github.com/playframework/Play20/wiki/Highlights https://github.com/playframework/Play20/wiki/Migration and also http://doc.akka.io/docs/akka/2.1.0-RC1/project/migration-guide-2.0.x-2.1.x.html

also asked here: https://groups.google.com/d/topic/play-framework/7VcwNea6QlM/discussion

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using sample code and Akka API I made fast test, works for me.

Comparing code between 2.0.4 and 2.1RC1 I can see there're only two changes in case of scheduler:

  1. replaced import

    // import akka.util.duration._
    import scala.concurrent.duration._
    
  2. added import:

    import play.api.libs.concurrent.Execution.Implicits._
    

app/controllers/Application.scala

package controllers

import play.api._
import play.api.mvc._
import play.libs.Akka

import akka.actor._
import scala.concurrent.duration._
import play.api.libs.concurrent.Execution.Implicits._

object Application extends Controller {

  def index = Action {

    // say hello
    Logger.info("hello, index action started")

    val Tick = "tick"
    val Tack = "tack"

    val tickActor = Akka.system.actorOf(Props(new Actor {
      def receive = {
        case Tick => Logger.info("that still ticks!")
        case Tack => Logger.warn("... 7 seconds after start, only once")
      }
    }))

    // Repeat every 5 seconds, start 5 seconds after start
    Akka.system.scheduler.schedule(
      5 seconds,
      5 seconds,
      tickActor,
      Tick
    )

    // do only once, 7 seconds after start
    Akka.system.scheduler.scheduleOnce(7 seconds, tickActor, Tack)

    Ok(views.html.index("Your new application is ready."))
  }

}

Edit

Nota bene, as I can see from Julien's post on the group, that's enough to import defaultContext only:

import play.api.libs.concurrent.Execution.Implicits.defaultContext

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...