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

Scala ScheduledExecutorService类代码示例

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

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



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

示例1: PollingJournalReader

//设置package包名称以及导入依赖的类
package fairshare.backend.eventsourcing.journals

import java.util.concurrent.ScheduledExecutorService

import fairshare.backend.eventsourcing._

import scala.concurrent.duration._
import scalaz.concurrent.{ Strategy, Task }
import scalaz.stream._

class PollingJournalReader[E](
    underlying: Journal[E],
    pollingFrequency: FiniteDuration,
    bufferSize: Int = PollingJournalReader.DefaultBufferSize
)(implicit executor: ScheduledExecutorService) {
  var alreadyReadEls: Int = 0
  val bus = async.boundedQueue[Fact[E]](bufferSize)(Strategy.Executor(executor))

  def listenUpdates: Process[Task, Unit] = getUnreadRetry(bufferSize, pollingFrequency).to(bus.enqueue)

  def readUpdates: Process[Task, Fact[E]] = bus.dequeue

  private[this] def queryUnderlying(from: Int, limit: Int): Task[Vector[Fact[E]]] =
    underlying.readAll(Index(alreadyReadEls), Index(alreadyReadEls + limit - 1)).runLog

  private[this] def getUnreadRetry(limit: Int, retryFreq: FiniteDuration): Process[Task, Fact[E]] =
    Process.await(queryUnderlying(alreadyReadEls, limit)) {
      got =>
        if (got.nonEmpty) {
          alreadyReadEls += got.length
          Process.emitAll(got).toSource ++ getUnreadRetry(limit, retryFreq)
        } else {
          time.sleep(retryFreq)(Strategy.Sequential, executor) ++ getUnreadRetry(limit, retryFreq)
        }
    }
}

object PollingJournalReader {
  val DefaultBufferSize = 10
} 
开发者ID:artempyanykh,项目名称:fair-share,代码行数:41,代码来源:PollingJournalReader.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: 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


示例4: unsafeSchedule

//设置package包名称以及导入依赖的类
package io.ahamdy.taskforce.scheduling

import java.util.concurrent.{Executors, ScheduledExecutorService}

import fs2.{Strategy, Stream, Task}

import scala.concurrent.duration.FiniteDuration
import cats.implicits._
import io.ahamdy.taskforce.common.Logging

trait Scheduler {
  def unsafeSchedule(period: FiniteDuration, task: Task[Unit], resultHandler: (Either[Throwable, Unit]) => Unit): Unit
  def shutdown: Unit
}

class SchedulerImpl(config: SchedulerConfig) extends Scheduler with Logging {

  private val executor: ScheduledExecutorService =
    Executors.newScheduledThreadPool(config.threadPoolSize, Strategy.daemonThreadFactory("Non-Block"))
  implicit val strategy: Strategy = Strategy.fromExecutor(executor)
  implicit val scheduler: fs2.Scheduler = fs2.Scheduler.fromScheduledExecutorService(executor)

  override def unsafeSchedule(period: FiniteDuration, task: Task[Unit], resultHandler: (Either[Throwable, Unit]) => Unit): Unit = {
    val neverFailingTask: Task[Unit] = task.attempt map {
      _.leftMap { err => logger.error(s"Unexpected error from a periodic task $err") }
    }

    (Stream.eval(neverFailingTask) ++ Stream.repeatEval(neverFailingTask.schedule(period))).run.unsafeRunAsync(resultHandler)
  }

  override def shutdown: Unit =
    executor.shutdown()
}

case class SchedulerConfig(threadPoolSize: Int) 
开发者ID:ahamdy88,项目名称:JobForce,代码行数:36,代码来源:Scheduler.scala


示例5: JvmMetricsCollectorStatsDService

//设置package包名称以及导入依赖的类
package com.springer.samatra.extras.metrics

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

import com.springer.samatra.extras.Logger
import com.timgroup.statsd.StatsDClient

class JvmMetricsCollectorStatsDService(jvmMetricsCollector: JvmMetricsCollector, statsDClient: StatsDClient, instance: String) extends Logger {
  private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor

  private def recordJvmStats() {
    try {
      jvmMetricsCollector.jvmGauges.foreach {
        case (aspect: String, value: java.lang.Long) => statsDClient.gauge(qualify(aspect), value); log.debug(s"${qualify(aspect)}, $value")
        case (aspect: String, value: java.lang.Double) => statsDClient.gauge(qualify(aspect), value); log.debug(s"${qualify(aspect)}, $value")
        case (aspect: String, value: Number) => log.error(s"Unable to quantify ${qualify(aspect)} of type ${value.getClass.getSimpleName}")
      }
      jvmMetricsCollector.jvmCounters.foreach {
        case (aspect: String, value: Number) => statsDClient.count(qualify(aspect), value.longValue()); log.debug(s"${qualify(aspect)}, $value")
      }
    }
    catch {
      case e: Exception => log.error("Error collecting jvm stats", Some(e))
    }
  }

  def initialise() {
    log.info("initialising jvm stats recording")
    scheduler.scheduleAtFixedRate(() => recordJvmStats(), 0, 10, TimeUnit.SECONDS)
  }

  private def qualify(aspect: String): String = "jvm." + instance + "." + aspect
} 
开发者ID:springernature,项目名称:samatra-extras,代码行数:34,代码来源:JvmMetricsCollectorStatsDService.scala


示例6: 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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Set类代码示例发布时间:2022-05-23
下一篇:
Scala UTF8String类代码示例发布时间: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