本文整理汇总了Scala中akka.actor.Cancellable类的典型用法代码示例。如果您正苦于以下问题:Scala Cancellable类的具体用法?Scala Cancellable怎么用?Scala Cancellable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Cancellable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ReceiveTimeout
//设置package包名称以及导入依赖的类
package akka.actor.dungeon
import ReceiveTimeout.emptyReceiveTimeoutData
import akka.actor.ActorCell
import akka.actor.ActorCell.emptyCancellable
import akka.actor.Cancellable
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration
private[akka] object ReceiveTimeout {
final val emptyReceiveTimeoutData: (Duration, Cancellable) = (Duration.Undefined, ActorCell.emptyCancellable)
}
private[akka] trait ReceiveTimeout { this: ActorCell ?
import ReceiveTimeout._
import ActorCell._
private var receiveTimeoutData: (Duration, Cancellable) = emptyReceiveTimeoutData
final def receiveTimeout: Duration = receiveTimeoutData._1
final def setReceiveTimeout(timeout: Duration): Unit = receiveTimeoutData = receiveTimeoutData.copy(_1 = timeout)
final def checkReceiveTimeout() {
val recvtimeout = receiveTimeoutData
//Only reschedule if desired and there are currently no more messages to be processed
if (!mailbox.hasMessages) recvtimeout._1 match {
case f: FiniteDuration ?
recvtimeout._2.cancel() //Cancel any ongoing future
val task = system.scheduler.scheduleOnce(f, self, akka.actor.ReceiveTimeout)(this.dispatcher)
receiveTimeoutData = (f, task)
case _ ? cancelReceiveTimeout()
}
else cancelReceiveTimeout()
}
final def cancelReceiveTimeout(): Unit =
if (receiveTimeoutData._2 ne emptyCancellable) {
receiveTimeoutData._2.cancel()
receiveTimeoutData = (receiveTimeoutData._1, emptyCancellable)
}
}
示例2: FakeActivity
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import akka.actor.{ActorRef, ActorSystem, Cancellable}
import logic.actors.fakeactivity.FakeActivityActor.FakeActivity
import play.api.inject.ApplicationLifecycle
import play.api.{Logger, _}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._
@Singleton
class FakeActivity @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle,
system: ActorSystem, @Named("fakeActivityActor") fakeActivityActor: ActorRef,
env: Environment) {
// This code is called when the application starts.
private val start: Instant = clock.instant
private var cancellableFakeActivity: Cancellable = null
Logger.info(s"FakeActivity: Starting application at ${start}.")
Logger.info("Mode: " + env.mode)
if (env.mode == Mode.Prod || env.mode == Mode.Dev) {
cancellableFakeActivity = system.scheduler.schedule(3 second, 10 minutes, fakeActivityActor, FakeActivity)
}
// When the application starts, register a stop hook with the
// ApplicationLifecyle object. The code inside the stop hook wil
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"FakeActivity: Stopping application at ${clock.instant} after ${runningTime}s.")
if (cancellableFakeActivity != null) {
cancellableFakeActivity.cancel()
}
Future.successful(())
}
}
示例3: ScheduleParser
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import akka.actor.{ActorRef, ActorSystem, Cancellable}
import play.api.Logger
import play.api._
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future
import logic.actors.schedule.CheckScheduleDateActor._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
@Singleton
class ScheduleParser @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle,system: ActorSystem , env: Environment,
@Named("checkSchedule") checkScheduleDateActor: ActorRef) {
// This code is called when the application starts.
private val start: Instant = clock.instant
private var cancellable1:Cancellable = null
Logger.info(s"ScheduleParser: Starting application at ${start}.")
if(env.mode == Mode.Prod || env.mode == Mode.Dev) {
cancellable1 = system.scheduler.schedule(2 second, 1 day ,checkScheduleDateActor , CheckScheduleDate)
}
// When the application starts, register a stop hook with the
// ApplicationLifecyle object. The code inside the stop hook wil
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"ScheduleParser: Stopping application at ${clock.instant} after ${runningTime}s.")
if(cancellable1 != null){
cancellable1.cancel()
}
Future.successful(())
}
}
示例4: NewsFeedReader
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import akka.actor.{ActorRef, ActorSystem, Cancellable}
import logic.actors.rss.DeleteNewsActor._
import logic.actors.rss.NewsReaderActor._
import play.api.{Logger, _}
import play.api.inject.ApplicationLifecycle
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._
@Singleton
class NewsFeedReader @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle,
system: ActorSystem, @Named("NewsReader") newsReaderActor: ActorRef,
@Named("deleteNews") deleteNewsActor: ActorRef, env: Environment) {
// This code is called when the application starts.
private val start: Instant = clock.instant
private var cancellableFeedParser: Cancellable = null
private var cancellableNewsDeleter: Cancellable = null
Logger.info(s"NewsFeedReader: Starting application at ${start}.")
Logger.info("Mode: " + env.mode)
if (env.mode == Mode.Prod || env.mode == Mode.Dev) {
cancellableFeedParser = system.scheduler.schedule(3 second, 1 minute, newsReaderActor, ReadNews)
cancellableNewsDeleter = system.scheduler.schedule(10 seconds, 6 hours, deleteNewsActor, DeleteNews)
}
// When the application starts, register a stop hook with the
// ApplicationLifecyle object. The code inside the stop hook wil
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"NewsFeedReader: Stopping application at ${clock.instant} after ${runningTime}s.")
if (cancellableFeedParser != null) {
cancellableFeedParser.cancel()
}
if (cancellableNewsDeleter != null) {
cancellableNewsDeleter.cancel()
}
Future.successful(())
}
}
示例5: DatabaseService
//设置package包名称以及导入依赖的类
package services
import java.time.{Clock, Instant}
import javax.inject._
import akka.actor.{ActorRef, ActorSystem, Cancellable}
import logic.actors.database.DatabaseActor.{StartUp, SyncDatabase}
import logic.actors.fakeactivity.FakeActivityActor.FakeActivity
import play.api.inject.ApplicationLifecycle
import play.api.{Logger, _}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration._
@Singleton
class DatabaseService @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle,
system: ActorSystem, @Named("databaseActor") databaseActor: ActorRef,
env: Environment) {
// This code is called when the application starts.
private val start: Instant = clock.instant
private var cancellableSyncActivity: Cancellable = null
Logger.info(s"Database: Starting application at ${start}.")
Logger.info("Mode: " + env.mode)
if (env.mode == Mode.Prod || env.mode == Mode.Dev) {
system.scheduler.scheduleOnce(1 second, databaseActor, StartUp)
cancellableSyncActivity = system.scheduler.schedule(30 second, 15 minutes, databaseActor, SyncDatabase)
}
// When the application starts, register a stop hook with the
// ApplicationLifecyle object. The code inside the stop hook wil
// be run when the application stops.
appLifecycle.addStopHook { () =>
val stop: Instant = clock.instant
val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
Logger.info(s"Database: Stopping application at ${clock.instant} after ${runningTime}s.")
if (cancellableSyncActivity != null) {
cancellableSyncActivity.cancel()
}
Future.successful(())
}
}
示例6: postStop
//设置package包名称以及导入依赖的类
package com.init6.connection
import java.util.concurrent.TimeUnit
import akka.actor.{ActorRef, Cancellable}
import com.init6.Init6Actor
import com.init6.users.KillConnection
import scala.concurrent.duration.Duration
trait Init6KeepAliveActor extends Init6Actor {
private var pingTask: Cancellable = _
protected var keptAlive = 0
override def postStop(): Unit = {
Option(pingTask).foreach(_.cancel())
super.postStop()
}
def keepAlive(actor: ActorRef, f: () => Unit): Unit = {
keepAlive(actor, f, 25, TimeUnit.SECONDS)
}
def keepAlive(actor: ActorRef, f: () => Unit, delay: Long, unit: TimeUnit): Unit = {
val pingDuration = Duration(25, TimeUnit.SECONDS)
import context.dispatcher
pingTask = system.scheduler.schedule(
pingDuration,
pingDuration
)({
if (keptAlive < 4) {
keptAlive += 1
f()
} else {
actor ! KillConnection
}
})
}
}
示例7: ServerAnnouncementActor
//设置package包名称以及导入依赖的类
package com.init6.servers
import java.util.concurrent.TimeUnit
import akka.actor.{Cancellable, Props}
import com.init6.Constants._
import com.init6.coders.commands.{BroadcastCommand, Command}
import com.init6.{Config, Init6Actor, Init6Component}
import scala.concurrent.duration.{Duration, FiniteDuration}
object ServerAnnouncementActor extends Init6Component {
def apply(timeToDrop: Long) =
system.actorOf(Props(classOf[ServerAnnouncementActor], timeToDrop), INIT6_SERVER_ANNOUNCEMENT_PATH)
}
case class RepeatingAnnoucement(message: String, duration: FiniteDuration) extends Command
class ServerAnnouncementActor(timeToDrop: Long) extends Init6Actor {
var announcement: Option[Cancellable] = None
override def preStart() = {
super.preStart()
if (!Config().Server.Chat.enabled) {
import context.dispatcher
system.scheduler.scheduleOnce(Duration(
timeToDrop - 15, TimeUnit.SECONDS
))({
usersActor ! BroadcastCommand(WILL_DROP_IN(Config().Server.host, 15))
})
}
}
override def receive = {
case RepeatingAnnoucement(message, duration) =>
import context.dispatcher
if (announcement.isDefined) {
announcement.get.cancel()
}
announcement = Some(system.scheduler.schedule(
Duration(0, TimeUnit.MILLISECONDS),
duration
)({
usersActor ! BroadcastCommand(message)
}))
}
}
示例8: receive
//设置package包名称以及导入依赖的类
package actors
import akka.actor._
import akka.event.LoggingReceive
import play.api.Logger
import play.api.libs.iteratee.Concurrent.Channel
import prickle.Pickle
import shared._
import shared.Utils.currentSeconds
import akka.actor.Cancellable
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
val keepAlive : Cancellable = ActorSystem(s"keepAlive").scheduler.schedule(0.seconds, SEND_INTERVAL){
backChannel push Pickle.intoString(CKeepAlive() : NetworkMessage)
if (currentSeconds - lastResponseTime >= CONNECTION_TIMEOUT_SECONDS) {
keepAlive.cancel()
mainServerActor ! CUserDisconnected()
//this prevents that in the last run there could be an nullPointer
if(context != null && self != null){
Logger.error(s"My Client ${context.self.toString()} didn't send anything for ${currentSeconds - lastResponseTime}s...")
context.stop(self)
}
}
}
def receive = LoggingReceive {
//Messages to the client go out through the backChannel
case n: ServerToClient =>
Logger.error("ServerConnectionActor-toClient-" + n)
backChannel push Pickle.intoString(n: NetworkMessage)
//Messages from the client go the the mainServerActor
case m: ClientToServer =>
Logger.error("ServerConnectionActor-fromClient-" + m)
m match {
case CKeepAlive() => lastResponseTime = currentSeconds
case _ => mainServerActor ! m
}
case x => Logger.error("Unknown packet in ConnectionHandlerActor - " + x)
}
}
object ServerConnectionActor {
def props(backChannel: Channel[String], mainServerActor: ActorRef): Props = Props(new ServerConnectionActor(backChannel, mainServerActor))
}
示例9: ReceiveTimeout
//设置package包名称以及导入依赖的类
package akka.actor.dungeon
import ReceiveTimeout.emptyReceiveTimeoutData
import akka.actor.ActorCell
import akka.actor.ActorCell.emptyCancellable
import akka.actor.Cancellable
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration
private[akka] object ReceiveTimeout {
final val emptyReceiveTimeoutData: (Duration, Cancellable) = (Duration.Undefined, ActorCell.emptyCancellable)
}
private[akka] trait ReceiveTimeout { this: ActorCell ?
import ReceiveTimeout._
import ActorCell._
private var receiveTimeoutData: (Duration, Cancellable) = emptyReceiveTimeoutData
final def receiveTimeout: Duration = receiveTimeoutData._1
final def setReceiveTimeout(timeout: Duration): Unit = receiveTimeoutData = receiveTimeoutData.copy(_1 = timeout)
final def checkReceiveTimeout() {
val recvtimeout = receiveTimeoutData
//Only reschedule if desired and there are currently no more messages to be processed
if (!mailbox.hasMessages) recvtimeout._1 match {
case f: FiniteDuration ?
recvtimeout._2.cancel() //Cancel any ongoing future
val task = system.scheduler.scheduleOnce(f, self, akka.actor.ReceiveTimeout)(this.dispatcher)
receiveTimeoutData = (f, task)
case _ ? cancelReceiveTimeout()
}
else cancelReceiveTimeout()
}
final def cancelReceiveTimeout(): Unit =
if (receiveTimeoutData._2 ne emptyCancellable) {
receiveTimeoutData._2.cancel()
receiveTimeoutData = (receiveTimeoutData._1, emptyCancellable)
}
}
示例10: JSIntervalTask
//设置package包名称以及导入依赖的类
package akka.util
import scala.concurrent.duration.FiniteDuration
import scala.scalajs.js.timers.{SetIntervalHandle, setInterval, clearInterval}
import akka.actor.Cancellable
class JSIntervalTask(interval: FiniteDuration, task: => Any) extends Cancellable {
private[this] var underlying: Option[SetIntervalHandle] =
Some(setInterval(interval)(task))
def isCancelled: Boolean = underlying.isEmpty
def cancel(): Boolean = {
if (isCancelled) false
else {
clearInterval(underlying.get)
underlying = None
true
}
}
}
object JSIntervalTask {
def apply(interval: FiniteDuration)(task: => Any): JSIntervalTask =
new JSIntervalTask(interval, task)
}
示例11: JSTimeoutThenIntervalTask
//设置package包名称以及导入依赖的类
package akka.util
import scala.concurrent.duration.{Duration, FiniteDuration}
import akka.actor.Cancellable
class JSTimeoutThenIntervalTask(initialDelay: FiniteDuration,
interval: FiniteDuration, task: => Any) extends Cancellable {
private[this] var underlying: Cancellable = JSTimeoutTask(initialDelay) {
underlying = JSIntervalTask(interval) {
task
}
task
}
def isCancelled: Boolean = underlying.isCancelled
def cancel(): Boolean = underlying.cancel()
}
object JSTimeoutThenIntervalTask {
def apply(initialDelay: FiniteDuration, interval: FiniteDuration)(
task: => Any): JSTimeoutThenIntervalTask =
new JSTimeoutThenIntervalTask(initialDelay, interval, task)
}
示例12: JSTimeoutTask
//设置package包名称以及导入依赖的类
package akka.util
import scala.concurrent.duration.FiniteDuration
import scala.scalajs.js.timers.{SetTimeoutHandle, setTimeout, clearTimeout}
import akka.actor.Cancellable
class JSTimeoutTask(delay: FiniteDuration, task: => Any) extends Cancellable {
private[this] var underlying: Option[SetTimeoutHandle] =
Some(setTimeout(delay)(task))
def isCancelled: Boolean = underlying.isEmpty
def cancel(): Boolean = {
if (isCancelled) false
else {
clearTimeout(underlying.get)
underlying = None
true
}
}
}
object JSTimeoutTask {
def apply(duration: FiniteDuration)(task: => Any): JSTimeoutTask =
new JSTimeoutTask(duration, task)
}
示例13: RobotsTxtLookUp
//设置package包名称以及导入依赖的类
package bridgeapp.crawler
import java.net.URI
import akka.actor.{ActorRef, ActorSystem, Cancellable}
import bridgeapp.crawler.execution._
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.duration._
import scala.util.control.NonFatal
class RobotsTxtLookUp(throttling: ActorRef) extends Runnable with LazyLogging {
override def run(): Unit = {
logger.warn(s" Lookup robots.txt")
val uri = new URI("https://rutracker.org/robots.txt")
val parser = new ResponseParser {
override def ->(response: Response): Unit = {
val body = new String(response.body)
Robots.parse(body) match {
case Left(error) =>
logger.error(s"Error parse robots txt file, $error ")
case Right(robots) =>
robots.nonGroupFields.map(s => (s.key, s.value)).toMap[String, String].get("Crawl-delay").fold() { delay =>
try {
val rate = Rate(1, delay.toFloat.second)
throttling ! SetRate(rate)
} catch {
case NonFatal(e) => logger.error("Error parse crawl delay directive in robots.txt. ", e)
}
}
}
}
}
val request = Request(uri, parser)
//throttling !! request
}
}
class RobotsTXTScheduleExecutor(robotsTxtLookUp: RobotsTxtLookUp)(implicit val actorSystem: ActorSystem) {
private implicit val prep = actorSystem.dispatcher.prepare()
private var instance: Cancellable = _
def execute(duration: FiniteDuration) = {
instance = actorSystem.scheduler.schedule(duration, duration, robotsTxtLookUp)
}
def cancel(): Unit = {
instance.cancel()
}
}
示例14: RealTime
//设置package包名称以及导入依赖的类
package com.outr.arango.managed
import akka.actor.{ActorSystem, Cancellable, Terminated}
import com.outr.arango.rest.LogEvent
import reactify.Observable
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
class RealTime(graph: Graph) {
private lazy val system = ActorSystem("Graph_realTime")
private var cancellable: Option[Cancellable] = None
lazy val events: Observable[LogEvent] = graph.monitor
def start(delay: FiniteDuration = 250.millis): Unit = synchronized {
assert(cancellable.isEmpty, "Graph.realTime is already started.")
cancellable = Some(system.scheduler.schedule(delay, delay) {
update()
})
}
def update(): Unit = graph.monitor.updateAndWait()
def stop(): Unit = {
cancellable.foreach(_.cancel())
cancellable = None
}
def started: Boolean = cancellable.nonEmpty
def shutdown(): Future[Terminated] = synchronized {
stop()
system.terminate()
}
}
示例15: WriteHandler
//设置package包名称以及导入依赖的类
package org.mystic.actors
import akka.actor.{Actor, ActorLogging, ActorRef, Cancellable}
import akka.io.Tcp.{PeerClosed, Write}
import akka.util.ByteString
import org.mystic.model._
class WriteHandler(whereToSend: ActorRef) extends Actor with ActorLogging {
var cancelable: Cancellable = _
override def receive: Receive = {
case Last10Minutes =>
log.info("trying to send 10 minutes data to the client")
val storage = context.system.actorSelection("user/storage")
storage ! AskFor10MData
case Data(data: List[Option[CandleDeal]]) =>
data.filter(_.isDefined).map(_.get).map(_.toJson).foreach(x => {
whereToSend ! Write(ByteString(x))
})
case Cancel(cancel) =>
log.info("setting the cancellable")
cancelable = cancel
case Last1Minute =>
log.info("trying to send last minute data to the client")
val storage = context.system.actorSelection("user/storage")
storage ! AskFor1MData
case PeerClosed =>
log.info("peer closed")
cancelable.cancel()
context stop self
case _ => log.error("something goes wrong in WriteHandler")
}
}