Skip to content

Instantly share code, notes, and snippets.

@mather
Last active May 25, 2016 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mather/07b092e9723bd9db5cb2 to your computer and use it in GitHub Desktop.
Save mather/07b092e9723bd9db5cb2 to your computer and use it in GitHub Desktop.
commons-daemonとAkkaでバッチアプリケーションの作成 ref: http://qiita.com/mather314/items/08e42057943e30aacb35
import org.apache.commons.daemon.{Daemon, DaemonContext}
class ApplicationDaemon(appName: String) extends Daemon {
private[this] val actorSystem = ActorSystem(appName)
override def init(context: DaemonContext) {}
override def destroy {}
override def start {
val reaper = actorSystem.actorOf(ReaperActor.props, "reaper")
val sampleActor = actorSystem.actorOf(SampleActor.props, "sample")
reaper ! ReaperActor.Watch(sampleActor)
sampleActor ! SampleActor.CountDown(10)
}
override def stop {
if (! actorSystem.isTerminated) {
// 通常はActorに終了指示を送るなど…
actorSystem.shutdown
}
}
}
Main.scala
ApplicationDaemon.scala
ReaperActor.scala
SampleActor.scala
object Main extends App {
new ApplicationDaemon("sample").start
}
import akka.actor.{Actor,ActorRef,Props,Terminated,PoisonPill}
class ReaperActor extends Actor {
private[this] val watchingActors = scala.collection.mutable.ArrayBuffer.empty[ActorRef]
def receive {
case ReaperActor.Watch(actor) =>
context.watch(actor)
watchingActors += actor
case Terminated(actor) =>
watchingActors -= actor
if (watchingActors.isEmpty) { context.system.shutdown }
// 通常は終了を知らせるメッセージを自前で定義して利用する
watchingActors.foreach(_ ! PoisonPill)
}
}
object ReaperActor {
def props = Props[ReaperActor]
case class Watch(actor: ActorRef)
}
import akka.actor.{Actor,ActorRef,Props}
class SampleActor extends Actor {
import SampleActor._
def receive {
case CountDown(0) =>
context.stop(self)
case CountDown(n) =>
println(n)
Thread.sleep(1000)
self ! CountDown(n-1)
}
}
object SampleActor {
def props = Props[SampleActor]
case class CountDown(n: Int) { require(n >= 0) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment