本文整理汇总了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
}
示例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)
}
示例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)
}
示例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)
示例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
}
示例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
}
}