Making a Java API for Scheduler (JScheduler) and an abstract class Scheduler that extends it, to make the Scheduler pluggable, moving it into AkkaApplication and migrating the code.

This commit is contained in:
Viktor Klang 2011-10-17 18:34:34 +02:00
parent 2270395d3f
commit 050411bf3b
10 changed files with 65 additions and 46 deletions

View file

@ -15,22 +15,49 @@
*/
package akka.actor
import akka.event.EventHandler
import akka.AkkaException
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent._
import java.lang.RuntimeException
import akka.util.Duration
object Scheduler {
case class SchedulerException(msg: String, e: Throwable) extends AkkaException(msg, e) {
def this(msg: String) = this(msg, null)
}
case class SchedulerException(msg: String, e: Throwable) extends AkkaException(msg, e)
trait JScheduler {
def schedule(receiver: ActorRef, message: Any, initialDelay: Long, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef]
def scheduleOnce(runnable: Runnable, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef]
def scheduleOnce(receiver: ActorRef, message: Any, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef]
}
abstract class Scheduler extends JScheduler {
def schedule(f: () Unit, initialDelay: Long, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef]
def scheduleOnce(f: () Unit, delay: Long, timeUnit: TimeUnit): ScheduledFuture[AnyRef]
def schedule(receiver: ActorRef, message: Any, initialDelay: Duration, delay: Duration): ScheduledFuture[AnyRef] =
schedule(receiver, message, initialDelay.toNanos, delay.toNanos, TimeUnit.NANOSECONDS)
def schedule(f: () Unit, initialDelay: Duration, delay: Duration): ScheduledFuture[AnyRef] =
schedule(f, initialDelay.toNanos, delay.toNanos, TimeUnit.NANOSECONDS)
def scheduleOnce(receiver: ActorRef, message: Any, delay: Duration): ScheduledFuture[AnyRef] =
scheduleOnce(receiver, message, delay.length, delay.unit)
def scheduleOnce(f: () Unit, delay: Duration): ScheduledFuture[AnyRef] =
scheduleOnce(f, delay.length, delay.unit)
}
class DefaultScheduler extends Scheduler {
private def createSendRunnable(receiver: ActorRef, message: Any, throwWhenReceiverExpired: Boolean): Runnable = new Runnable {
def run = {
receiver ! message
if (throwWhenReceiverExpired && receiver.isShutdown) throw new ActorKilledException("Receiver was terminated")
}
}
private[akka] val service = Executors.newSingleThreadScheduledExecutor(SchedulerThreadFactory)
private def createSendRunnable(receiver: ActorRef, message: Any, throwWhenReceiverExpired: Boolean): Runnable = {
new Runnable { def run = receiver ! message }
}
/**
* Schedules to send the specified message to the receiver after initialDelay and then repeated after delay.
* The returned java.util.concurrent.ScheduledFuture can be used to cancel the