• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala ScheduledFuture类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.util.concurrent.ScheduledFuture的典型用法代码示例。如果您正苦于以下问题:Scala ScheduledFuture类的具体用法?Scala ScheduledFuture怎么用?Scala ScheduledFuture使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ScheduledFuture类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: DataProducer

//设置package包名称以及导入依赖的类
package org.hpi.esb.datasender

import java.util.concurrent.{ScheduledFuture, ScheduledThreadPoolExecutor, TimeUnit}

import org.apache.kafka.clients.producer.KafkaProducer
import org.hpi.esb.commons.util.Logging
import org.hpi.esb.datasender.config.Configurable
import org.hpi.esb.datasender.output.writers.DatasenderRunResultWriter
import org.hpi.esb.util.OffsetManagement


class DataProducer(resultHandler: DatasenderRunResultWriter, kafkaProducer: KafkaProducer[String, String],
                   dataReader: DataReader, topics: List[String], numberOfThreads: Int,
                   sendingInterval: Int, sendingIntervalTimeUnit: TimeUnit,
                   duration: Long, durationTimeUnit: TimeUnit, singleColumnMode: Boolean) extends Logging with Configurable {


  val executor: ScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(numberOfThreads)
  val producerThread = new DataProducerThread(this, kafkaProducer, dataReader, topics,
    singleColumnMode, duration, durationTimeUnit)

  val topicOffsets = getTopicOffsets()

  var t: ScheduledFuture[_] = _

  def shutDown(): Unit = {
    t.cancel(false)
    dataReader.close()
    kafkaProducer.close()
    executor.shutdown()
    logger.info("Shut data producer down.")
    val expectedRecordNumber = producerThread.numberOfRecords
    resultHandler.outputResults(topicOffsets, expectedRecordNumber)
  }

  def execute(): Unit = {
    val initialDelay = 0
    t = executor.scheduleAtFixedRate(producerThread, initialDelay, sendingInterval, sendingIntervalTimeUnit)
    val allTopics = topics.mkString(" ")
    logger.info(s"Sending records to following topics: $allTopics")
  }

  def getTopicOffsets(): Map[String, Long] = {
    topics.map(topic => {
      val currentOffset = OffsetManagement.getNumberOfMessages(topic, partition = 0)
      topic -> currentOffset
    }).toMap[String, Long]
  }
} 
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:50,代码来源:DataProducer.scala


示例2: DelegatingScheduledExecutorService

//设置package包名称以及导入依赖的类
package one.lockstep.util.concurrent

import java.util
import java.util.concurrent.{Callable, ScheduledExecutorService, ScheduledFuture}

import one.lockstep.util.japi._

import scala.concurrent.duration._

class DelegatingScheduledExecutorService(service: ScheduledExecutorService)
  extends ScheduledExecutorService {
  def prepareSchedule(delay: Long, unit: TimeUnit): Unit = ()
  override def scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = {
    prepareSchedule(List(initialDelay, period).max, unit)
    service.scheduleAtFixedRate(command, initialDelay, period, unit)
  }
  override def schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture[_] = {
    prepareSchedule(delay, unit)
    service.schedule(command, delay, unit)
  }
  override def schedule[V](callable: Callable[V], delay: Long, unit: TimeUnit): ScheduledFuture[V] = {
    prepareSchedule(delay, unit)
    service.schedule(callable, delay, unit)
  }
  override def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledFuture[_] = {
    prepareSchedule(List(initialDelay, delay).max, unit)
    service.scheduleWithFixedDelay(command, initialDelay, delay, unit)
  }
  override def shutdown(): Unit = service.shutdown()
  override def isTerminated: Boolean = service.isTerminated
  override def awaitTermination(timeout: Long, unit: TimeUnit): Boolean =
    service.awaitTermination(timeout, unit)
  override def shutdownNow(): util.List[Runnable] = service.shutdownNow()
  override def invokeAll[T](tasks: util.Collection[_ <: Callable[T]]): util.List[JFuture[T]] =
    service.invokeAll(tasks)
  override def invokeAll[T](tasks: util.Collection[_ <: Callable[T]], timeout: Long, unit: TimeUnit): util.List[JFuture[T]] =
    service.invokeAll(tasks, timeout, unit)
  override def invokeAny[T](tasks: util.Collection[_ <: Callable[T]]): T = service.invokeAny(tasks)
  override def invokeAny[T](tasks: util.Collection[_ <: Callable[T]], timeout: Long, unit: TimeUnit): T =
    service.invokeAny(tasks, timeout, unit)
  override def isShutdown: Boolean = service.isShutdown
  override def submit[T](task: Callable[T]): JFuture[T] = service.submit(task)
  override def submit[T](task: Runnable, result: T): JFuture[T] = service.submit(task, result)
  override def submit(task: Runnable): JFuture[_] = service.submit(task)
  override def execute(command: Runnable): Unit = service.execute(command)
} 
开发者ID:lockstep-one,项目名称:vault,代码行数:47,代码来源:DelegatingScheduledExecutorService.scala


示例3: ExtensionSignaturesLoader

//设置package包名称以及导入依赖的类
package com.wavesplatform.network

import java.util.concurrent.ScheduledFuture

import com.wavesplatform.state2.ByteStr
import io.netty.channel.{ChannelDuplexHandler, ChannelHandlerContext, ChannelPromise}
import scorex.utils.ScorexLogging

import scala.concurrent.duration.FiniteDuration

class ExtensionSignaturesLoader(syncTimeout: FiniteDuration, peerDatabase: PeerDatabase)
  extends ChannelDuplexHandler with ScorexLogging {

  private var currentTimeout = Option.empty[ScheduledFuture[Unit]]
  private var lastKnownSignatures = Seq.empty[ByteStr]

  override def channelRead(ctx: ChannelHandlerContext, msg: AnyRef) = msg match {
    case s: Signatures =>
      val (known, unknown) = s.signatures.span(id => lastKnownSignatures.contains(id))
      currentTimeout.foreach(_.cancel(true))
      currentTimeout = None
      known.lastOption.foreach { lastKnown =>
        log.debug(s"${id(ctx)} Got extension with ${known.length}/${s.signatures.length} known signatures")
        ctx.fireChannelRead(ExtensionIds(lastKnown, unknown))
      }
    case _ => super.channelRead(ctx, msg)
  }

  override def channelInactive(ctx: ChannelHandlerContext) = {
    currentTimeout.foreach(_.cancel(false))
    currentTimeout = None
  }

  override def write(ctx: ChannelHandlerContext, msg: AnyRef, promise: ChannelPromise) = msg match {
    case LoadBlockchainExtension(sigs) if currentTimeout.isEmpty =>
      lastKnownSignatures = sigs

      log.debug(s"${id(ctx)} Loading extension, last ${sigs.length} are ${formatSignatures(sigs)}")

      currentTimeout = Some(ctx.executor().schedule(syncTimeout) {
        if (currentTimeout.nonEmpty && ctx.channel().isActive) {
          peerDatabase.blacklistAndClose(ctx.channel(),"Timeout expired while loading extension")
        }
      })

      ctx.writeAndFlush(GetSignatures(sigs), promise)

    case LoadBlockchainExtension(_) =>
      log.debug(s"${id(ctx)} Received request to load signatures while waiting for extension, ignoring for now")
      promise.setSuccess()

    case _ => super.write(ctx, msg, promise)
  }
} 
开发者ID:wavesplatform,项目名称:Waves,代码行数:55,代码来源:ExtensionSignaturesLoader.scala


示例4: removeExpired

//设置package包名称以及导入依赖的类
package ru.tinkoff.cache

import java.util.concurrent.{ScheduledExecutorService, ScheduledFuture, TimeUnit}

import akka.actor.{Scheduler, Cancellable => AkkaCancellable}


trait StorageCleaner {
  def removeExpired(): Unit
  def scheduleCleaning(): Cancellable
}

trait Cancellable {
  def cancel(): Boolean
  def isCancelled: Boolean
}

object Cancellable {
  implicit def fromAkka(ac: AkkaCancellable): Cancellable = new Cancellable {
    def cancel(): Boolean = ac.cancel()
    def isCancelled: Boolean = ac.isCancelled
  }

  implicit def fromJava(sf: ScheduledFuture[_]): Cancellable = new Cancellable {
    def cancel() = sf.cancel(false)
    def isCancelled = sf.isCancelled
  }

  object empty extends Cancellable {
    val cancel = false
    val isCancelled = true
  }
}

trait NoCleaner extends StorageCleaner {
  def scheduleCleaning() = Cancellable.empty
}

trait AkkaSchedulerCleaner extends StorageCleaner { this: CacheStorage =>
  def scheduler: Scheduler
  def settings: CacheConfig
  def scheduleCleaning() = scheduler.schedule(settings.cleanInterval, settings.cleanInterval) {
    removeExpired()
  }(cacheContext)
}

trait JavaSchedulerCleaner extends StorageCleaner {
  def scheduler: ScheduledExecutorService
  def settings: CacheConfig
  def scheduleCleaning() = scheduler.scheduleAtFixedRate(new Runnable {
    def run() = removeExpired()
  }, settings.cleanInterval.toMillis, settings.cleanInterval.toMillis, TimeUnit.MILLISECONDS)
} 
开发者ID:TinkoffCreditSystems,项目名称:MacroCache,代码行数:54,代码来源:StorageCleaner.scala


示例5: MockScheduledExecutorService

//设置package包名称以及导入依赖的类
package com.twitter.jvm

import java.util.concurrent.{AbstractExecutorService, Callable, ScheduledExecutorService, ScheduledFuture, TimeUnit}

import scala.collection.mutable

// A mostly empty implementation so that we can successfully
// mock it.
class MockScheduledExecutorService extends AbstractExecutorService with ScheduledExecutorService {
  val schedules = mutable.Buffer[(Runnable, Long, Long, TimeUnit)]()

  def schedule[V](c: Callable[V], delay: Long, unit: TimeUnit) = throw new Exception
  def schedule(command: Runnable, delay: Long, unit: TimeUnit) = throw new Exception
  def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit) =
    throw new Exception
  def execute(command: Runnable) = throw new Exception
  def awaitTermination(timeout: Long, unit: TimeUnit) = throw new Exception
  def isTerminated() = throw new Exception
  def isShutdown() = throw new Exception
  def shutdownNow() = throw new Exception
  def shutdown() = throw new Exception

  def scheduleAtFixedRate(r: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = {
    schedules += ((r, initialDelay, period, unit))
    null
  }
} 
开发者ID:lanshuijuntuan,项目名称:Java.util,代码行数:28,代码来源:MockScheduledExecutorService.scala


示例6: RichScheduledExecutorService

//设置package包名称以及导入依赖的类
package com.kakao.mango.concurrent

import java.util.concurrent.{Callable, ScheduledFuture, TimeUnit, ScheduledExecutorService}

import scala.concurrent.duration.Duration
import scala.concurrent.duration._
import scala.language.postfixOps


class RichScheduledExecutorService(underlying: ScheduledExecutorService) extends RichExecutorService(underlying) with ScheduledExecutorService {

  def scheduleIn[T](delay: Duration)(command: => T): ScheduledFuture[T] = schedule(new Callable[T] {
    override def call(): T = command
  }, delay.toMillis, TimeUnit.MILLISECONDS)

  def withFixedRate[T](rate: Duration, initialDelay: Duration = 0.second)(command: => Unit) = scheduleAtFixedRate(new Runnable {
    override def run(): Unit = command
  }, initialDelay.toMillis, rate.toMillis, TimeUnit.MILLISECONDS)

  def withFixedDelay[T](delay: Duration, initialDelay: Duration = 0.second)(command: => Unit) = scheduleWithFixedDelay(new Runnable {
    override def run(): Unit = command
  }, initialDelay.toMillis, delay.toMicros, TimeUnit.MILLISECONDS)

  // delegating to underlying
  override def schedule(command: Runnable, delay: Long, unit: TimeUnit): ScheduledFuture[_] = underlying.schedule(wrap(command), delay, unit)
  override def scheduleAtFixedRate(command: Runnable, initialDelay: Long, period: Long, unit: TimeUnit): ScheduledFuture[_] = underlying.scheduleAtFixedRate(wrap(command), initialDelay, period, unit)
  override def schedule[V](callable: Callable[V], delay: Long, unit: TimeUnit): ScheduledFuture[V] = underlying.schedule(wrap(callable), delay, unit)
  override def scheduleWithFixedDelay(command: Runnable, initialDelay: Long, delay: Long, unit: TimeUnit): ScheduledFuture[_] = underlying.scheduleWithFixedDelay(wrap(command), initialDelay, delay, unit)
} 
开发者ID:kakao,项目名称:mango,代码行数:30,代码来源:RichScheduledExecutorService.scala


示例7: ExtensionSignaturesLoader

//设置package包名称以及导入依赖的类
package com.wavesplatform.network

import java.util.concurrent.ScheduledFuture

import com.wavesplatform.state2.ByteStr
import io.netty.channel.{ChannelDuplexHandler, ChannelHandlerContext, ChannelPromise}
import scorex.utils.ScorexLogging

import scala.concurrent.duration.FiniteDuration

class ExtensionSignaturesLoader(syncTimeout: FiniteDuration, peerDatabase: PeerDatabase)
  extends ChannelDuplexHandler with ScorexLogging {

  private var currentTimeout = Option.empty[ScheduledFuture[Unit]]
  private var lastKnownSignatures = Seq.empty[ByteStr]

  override def channelRead(ctx: ChannelHandlerContext, msg: AnyRef) = msg match {
    case s: Signatures =>
      val (known, unknown) = s.signatures.span(id => lastKnownSignatures.contains(id))
      currentTimeout.foreach(_.cancel(true))
      currentTimeout = None
      known.lastOption.foreach { lastKnown =>
        log.debug(s"${id(ctx)} Got extension with ${known.length}/${s.signatures.length} known signatures")
        ctx.fireChannelRead(ExtensionIds(lastKnown, unknown))
      }
    case _ => super.channelRead(ctx, msg)
  }

  override def channelInactive(ctx: ChannelHandlerContext) = {
    currentTimeout.foreach(_.cancel(false))
    currentTimeout = None
  }

  override def write(ctx: ChannelHandlerContext, msg: AnyRef, promise: ChannelPromise) = msg match {
    case LoadBlockchainExtension(sigs) if currentTimeout.isEmpty =>
      lastKnownSignatures = sigs

      log.debug(s"${id(ctx)} Loading extension, last ${sigs.length} are [${sigs.head}..${sigs.last}]")

      currentTimeout = Some(ctx.executor().schedule(syncTimeout) {
        if (currentTimeout.nonEmpty && ctx.channel().isActive) {
          peerDatabase.blacklistAndClose(ctx.channel(),"Timeout expired while loading extension")
        }
      })

      ctx.writeAndFlush(GetSignatures(sigs), promise)

    case LoadBlockchainExtension(sigs) =>
      log.debug(s"${id(ctx)} Received request to load signatures while waiting for extension, ignoring for now")
      promise.setSuccess()

    case _ => super.write(ctx, msg, promise)
  }
} 
开发者ID:mikepijn,项目名称:wavesnode,代码行数:55,代码来源:ExtensionSignaturesLoader.scala



注:本文中的java.util.concurrent.ScheduledFuture类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala JsonInclude类代码示例发布时间:2022-05-23
下一篇:
Scala ChannelHandlerContext类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap