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

Scala Timer类代码示例

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

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



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

示例1: Metrics

//设置package包名称以及导入依赖的类
package eu.inn.kafka.mimic

import java.net.{InetAddress, InetSocketAddress}
import java.util.concurrent.TimeUnit
import java.util.{Timer, TimerTask}

import com.codahale.metrics.graphite.{Graphite, GraphiteReporter}
import nl.grons.metrics.scala.{InstrumentedBuilder, MetricName}

object Metrics extends Logging {
  val metricRegistry = new com.codahale.metrics.MetricRegistry()

  def startReporter(host: String, port: Int, prefix: String, reportPeriod: Long) = {

    val graphite = new Graphite(new InetSocketAddress(host, port))

    val reporter = GraphiteReporter.forRegistry(metricRegistry)
      .prefixedWith(prefix + "." + InetAddress.getLocalHost.getHostName.replaceAll("\\.", "-"))
      .build(graphite)

    new Timer("graphite-reporter-timer").schedule(
      new TimerTask { def run() = reporter.report() },
      reportPeriod,
      reportPeriod
    )
  }
}

trait Metrics extends InstrumentedBuilder {
  override lazy val metricBaseName = MetricName("kafka-mimic")

  lazy val metricRegistry = Metrics.metricRegistry
}

trait MetricsComponent extends Metrics with Logging {

  this: ConfigComponent =>

  def startMetricsReporting() = {
    if (config.hasPath("enabled") && config.getBoolean("enabled")) {
      val host = config.getString("host")
      val port = config.getInt("port")
      log.info(s"Starting graphite reporter for $host:$port")
      Metrics.startReporter(
        host,
        port,
        config.getString("prefix"),
        config.getDuration("report-period", TimeUnit.MILLISECONDS)
      )
    }

    metrics.gauge("heartbeat") { 1 }
  }
} 
开发者ID:InnovaCo,项目名称:kafka-mimic,代码行数:55,代码来源:Metrics.scala


示例2: JavaTimerScheduler

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

import java.util.{Timer, TimerTask}

import korolev.Async
import korolev.Async.AsyncOps
import korolev.util.Scheduler.{Cancel, JobHandler}

import scala.concurrent.duration.FiniteDuration
import scala.language.higherKinds
import scala.util.Success


final class JavaTimerScheduler[F[+_]: Async] extends Scheduler[F] {

  private val timer = new Timer()
  private val async = Async[F]

  def scheduleOnce[T](delay: FiniteDuration)(job: => T): JobHandler[F, T] = {
    val promise = Async[F].promise[T]
    val task = new TimerTask {
      def run(): Unit = {
        val task = async.fork {
          val result = job // Execute a job
          promise.complete(Success(result))
        }
        task.run()
      }
    }
    timer.schedule(task, delay.toMillis)
    JobHandler(
      cancel = () => task.cancel,
      result = promise.future
    )
  }

  def schedule[U](interval: FiniteDuration)(job: => U): Cancel = {
    val task = new TimerTask {
      def run(): Unit = async.fork(job).run()
    }
    val millis = interval.toMillis
    timer.schedule(task, millis, millis)
    () => task.cancel
  }
} 
开发者ID:techyogillc,项目名称:ServerSideScalaCode,代码行数:46,代码来源:JavaTimerScheduler.scala


示例3: asyncExit

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.base

import java.util.{ Timer, TimerTask }

import akka.Done
import com.typesafe.scalalogging.StrictLogging

import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future, _ }


  def asyncExit(
    exitCode: Int = RichRuntime.FatalErrorSignal,
    waitForExit: FiniteDuration = RichRuntime.DefaultExitDelay)(implicit ec: ExecutionContext): Future[Done] = {
    val timer = new Timer()
    val promise = Promise[Done]()
    timer.schedule(new TimerTask {
      override def run(): Unit = {
        logger.info("Halting JVM")
        promise.success(Done)
        // do nothing in tests: we can't guarantee we can block the exit
        if (!sys.props.get("java.class.path").exists(_.contains("test-classes"))) {
          Runtime.getRuntime.halt(exitCode)
        }
      }
    }, waitForExit.toMillis)
    Future(sys.exit(exitCode))
    promise.future
  }
}

object RichRuntime {
  val FatalErrorSignal = 137
  val DefaultExitDelay = 10.seconds
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:36,代码来源:RichRuntime.scala


示例4: JavaTimerScheduler

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

import java.util.{Timer, TimerTask}

import korolev.Async
import korolev.Async.AsyncOps
import korolev.util.Scheduler.{Cancel, JobHandler}

import scala.concurrent.duration.FiniteDuration
import scala.util.Success

final class JavaTimerScheduler[F[+_]: Async] extends Scheduler[F] {

  private val timer = new Timer()
  private val async = Async[F]

  def scheduleOnce[T](delay: FiniteDuration)(job: => T): JobHandler[F, T] = {
    val promise = Async[F].promise[T]
    val task = new TimerTask {
      def run(): Unit = {
        val task = async.fork {
          val result = job // Execute a job
          promise.complete(Success(result))
        }
        task.runIgnoreResult()
      }
    }
    timer.schedule(task, delay.toMillis)
    JobHandler(
      cancel = () => { task.cancel(); () },
      result = promise.future
    )
  }

  def schedule[U](interval: FiniteDuration)(job: => U): Cancel = {
    val task = new TimerTask {
      def run(): Unit = async.fork(job).runIgnoreResult()
    }
    val millis = interval.toMillis
    timer.schedule(task, millis, millis)
    () => { task.cancel(); () }
  }
} 
开发者ID:fomkin,项目名称:korolev,代码行数:44,代码来源:JavaTimerScheduler.scala


示例5: Main

//设置package包名称以及导入依赖的类
import java.text.SimpleDateFormat
import java.util.{Date, Timer, TimerTask}


object Main extends App {

  val fortuneBot = new FortuneBot
  val timer = new Timer
  val timeHigh =  10800000
  val timeLow =    1800000

//  val timeHigh =  72000
//  val timeLow = 18000

  class BotAction extends TimerTask {
    override def run() = generateAndSendTweet()
  }

  def nextTimeExecution () : Int = {scala.util.Random.nextInt(timeHigh) + timeLow}

  def formatMillisecondsToReadableTime(milliseconds : Long): String ={
    val now = new Date
    val totalTime = now.getTime + milliseconds
    val formater = new SimpleDateFormat("HH:mm:ss")
    val readableTime = formater.format(new Date(totalTime))
    println(s"[FORTUNE BOT] Next execution time : [$milliseconds] milliseconds")
    println(s"[FORTUNE BOT] Next execution exactly at -> [$readableTime]")
    readableTime
  }


  def generateAndSendTweet(){
    println("###############################")
    val fortune = fortuneBot.extractFortune()
    val twit = fortuneBot.formatTwit(fortune)
    twit.foreach(fortuneBot.publishTwit)
    val nextTime = nextTimeExecution()
    formatMillisecondsToReadableTime(nextTime)
    timer.schedule(new BotAction, nextTime)

  }

  (new BotAction).run()

} 
开发者ID:M0rdr3d,项目名称:FortuneBot,代码行数:46,代码来源:Main.scala


示例6: Task

//设置package包名称以及导入依赖的类
package model

object Task {
	import java.util.{Timer, TimerTask}
	def schedule(runnable: Runnable) = new Timer().schedule(new TimerTask {
		override def run() = runnable.run()
	}, 0)
	def repeat(delay: Long, period: Long, runnable: Runnable) = new Timer {
		scheduleAtFixedRate(new TimerTask {
			override def run() = runnable.run()
		}, delay, period)
	}
} 
开发者ID:nextzlog,项目名称:nabe,代码行数:14,代码来源:Task.scala


示例7: extract

//设置package包名称以及导入依赖的类
package lol.http

import java.util.{ Timer, TimerTask }

import scala.concurrent.{ Future, Promise, ExecutionContext }
import scala.concurrent.duration.{ FiniteDuration }

package object internal {

  // Sometimes we don't want to pollute the API by asking an executionContext, so
  // we will use this one internally. It will be only used for internal non-blocking operations when
  // no user code is involved.
  val nonBlockingInternalExecutionContext = scala.concurrent.ExecutionContext.Implicits.global

  def extract(url: String): (String, String, Int, String, Option[String]) = {
    val url0 = new java.net.URL(url)
    val path = if(url0.getPath.isEmpty) "/" else url0.getPath
    val port = url0.getPort
    val host = url0.getHost
    val scheme = url0.getProtocol
    val queryString = Option(url0.getQuery)
    (scheme, host, if(port < 0) url0.getDefaultPort else port, path, queryString)
  }

  def guessContentType(fileName: String): String = {
    fileName.split("[.]").lastOption.collect {
      case "css"          => "text/css"
      case "htm" | "html" => "text/html"
      case "txt"          => "text/plain"
      case "js"           => "application/javascript"
      case "gif"          => "images/gif"
      case "png"          => "images/png"
      case "jpg" | "jpeg" => "images/jpeg"
    }.getOrElse("application/octet-stream")
  }

  lazy val timer = new Timer("lol.http.internal.timer", true)
  def timeout[A](a: => A, duration: FiniteDuration): Future[A] = {
    val e = Promise[A]
    timer.schedule(new TimerTask { def run(): Unit = e.success(a) }, duration.toMillis)
    e.future
  }

  def withTimeout[A](a: Future[A], duration: FiniteDuration, onTimeout: () => Unit = () => ())(implicit e: ExecutionContext): Future[A] = {
    Future.firstCompletedOf(Seq(a.map(Right.apply), timeout(Left(()), duration))).
      flatMap {
        case Right(x) =>
          Future.successful(x)
        case Left(_) =>
          onTimeout()
          Future.failed(Error.Timeout(duration))
      }
  }

} 
开发者ID:criteo,项目名称:lolhttp,代码行数:56,代码来源:internal.scala


示例8: Tests

//设置package包名称以及导入依赖的类
package lol.http

import org.scalatest._

import java.util.{ Timer, TimerTask }

import scala.util.{ Try, Success, Failure }

import scala.concurrent.{ Await, Promise, Future, ExecutionContext }
import scala.concurrent.duration._

abstract class Tests extends FunSuite with Matchers with OptionValues with Inside with Inspectors {
  val Pure = Tag("Pure")
  val Slow = Tag("Slow")
  def await[A](atMost: FiniteDuration = 30 seconds)(a: Future[A]): A = Await.result(a, atMost)
  def withServer(server: Server)(test: Server => Unit) = try { test(server) } finally { server.stop() }
  def success[A](a: A) = Future.successful(a)
  def status(req: Request, atMost: FiniteDuration = 30 seconds, followRedirects: Boolean = true)(implicit e: ExecutionContext, ssl: SSL.ClientConfiguration): Int = {
    await(atMost) { Client.run(req, followRedirects = followRedirects, timeout = atMost)(res => success(res.status)) }
  }
  def contentString(req: Request, atMost: FiniteDuration = 30 seconds, followRedirects: Boolean = true)(implicit e: ExecutionContext, ssl: SSL.ClientConfiguration): String = {
    await(atMost) { Client.run(req, followRedirects = followRedirects, timeout = atMost)(_.readAs[String]) }
  }
  def headers(req: Request, atMost: FiniteDuration = 30 seconds)(implicit e: ExecutionContext, ssl: SSL.ClientConfiguration): Map[HttpString,HttpString] = {
    await(atMost) { Client.run(req, timeout = atMost)(res => Future.successful(res.headers)) }
  }
  def getString(content: Content, codec: String = "utf-8") = new String(getBytes(content).toArray, codec)
  def getBytes(content: Content): Vector[Byte] = content.stream.runLog.unsafeRunSync()
  def bytes(data: Int*): Seq[Byte] = data.map(_.toByte)
  val timer = new Timer(true)
  def timeout[A](d: FiniteDuration, a: A): Future[A] = {
    val p = Promise[A]
    timer.schedule(new TimerTask { def run() = p.success(a) }, d.toMillis)
    p.future
  }
  def eventually[A](assertion: => A, timeout: FiniteDuration = 5 seconds): A = {
    val start = System.currentTimeMillis
    def go(): A = Try(assertion) match {
      case Success(a) => a
      case Failure(e) =>
        if(System.currentTimeMillis - start < timeout.toMillis) go() else throw e
    }
    go()
  }
} 
开发者ID:criteo,项目名称:lolhttp,代码行数:46,代码来源:Tests.scala


示例9: delayedFailure

//设置package包名称以及导入依赖的类
package scalaDemo.threadConcurrency

import java.util.{Timer, TimerTask}

import scala.concurrent._


  def delayedFailure(secs: Int, msg: String): Future[Int] = {
    val result = Promise[Int]//Promise ???????,??????? Promise ????????????
    timer.schedule(new TimerTask() {
      def run() = {
        result.failure(new IllegalArgumentException(msg))
      }
    }, secs * 1000)
    
    //Future ???????????????????????????????? Callback ????????????????????
    result.future
  }
} 
开发者ID:tophua,项目名称:spark1.52,代码行数:20,代码来源:TimedEvent.scala


示例10: TimerSchedule

//设置package包名称以及导入依赖的类
package scalaDemo

import java.text.SimpleDateFormat
import java.util.{Timer, TimerTask}

object TimerSchedule {
  
    val fTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
    val d1 = fTime.parse("2005/12/30 14:10:00");
    val timer: Timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
      override def run(): Unit = {
        System.out.println("this is task you do6");
      }
    }, d1, 3 * 60 * 1000);

  }
} 
开发者ID:tophua,项目名称:spark1.52,代码行数:19,代码来源:TimerSchedule.scala


示例11: delayedFailure

//设置package包名称以及导入依赖的类
package scalaDemo

import java.util.{Timer, TimerTask}

import scala.concurrent._

  def delayedFailure(secs: Int, msg: String): Future[Int] = {
    val result = Promise[Int]
    timer.schedule(new TimerTask() {
      def run() = {
        result.failure(new IllegalArgumentException(msg))
      }
    }, secs * 10)
    result.future
  }
  delayedSuccess(1,timer)
  delayedFailure(2,"delayedFailure")
} 
开发者ID:tophua,项目名称:spark1.52,代码行数:19,代码来源:PromiseTimedEventTestApp.scala


示例12: Backoff

//设置package包名称以及导入依赖的类
package caustic.runtime

import java.util.{Timer, TimerTask}
import java.util.concurrent.ThreadLocalRandom
import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.concurrent.duration._

object Backoff {

  // Retry scheduler.
  lazy val scheduler: Timer = new Timer(true)

  
  def exponential(
    times: Int,
    initial: FiniteDuration,
    maximum: FiniteDuration
  ): Stream[FiniteDuration] = {
    require(initial > Duration.Zero, "Initial duration must be positive.")
    require(maximum >= initial, "Maximum duration must be greater than the initial.")
    require(times > 0, "Times must be a positive integer.")

    def next(attempt: Int): Stream[FiniteDuration] = {
      val shift = math.min(attempt, 62)
      val maxBackoff = maximum.min(initial * (1L << shift))
      val random = Duration.fromNanos(ThreadLocalRandom.current().nextLong(maxBackoff.toNanos))
      if (attempt >= times) Stream.empty else random #:: next(attempt + 1)
    }

    initial #:: next(1)
  }

} 
开发者ID:ashwin153,项目名称:caustic,代码行数:34,代码来源:Backoff.scala


示例13: FutureUtils

//设置package包名称以及导入依赖的类
package flumina.client

import java.util.{Timer, TimerTask}

import scala.concurrent.{ExecutionContext, Future, Promise}
import scala.concurrent.duration.FiniteDuration
import scala.util.Try

object FutureUtils {

  private val timer = new Timer()

  def delay(duration: FiniteDuration): Future[Unit] = {
    val promise = Promise[Unit]()
    val task = new TimerTask {
      def run() = promise.complete(Try(()))
    }
    timer.schedule(task, duration.toMillis)
    promise.future
  }

  def delayFuture[A](duration: FiniteDuration, f: => Future[A])(implicit EC: ExecutionContext): Future[A] =
    delay(duration).flatMap(_ => f)

} 
开发者ID:vectos,项目名称:flumina,代码行数:26,代码来源:FutureUtils.scala


示例14: TransitionNumerizer

//设置package包名称以及导入依赖的类
package numerizer

import java.util.{TimerTask, Timer}

import graph.{Vertex, ReactionMap}


class TransitionNumerizer(rmap:ReactionMap, from:Numerizer, to:Numerizer, updater:(Unit=>Unit), setter:(Numerizer=>Unit))
  extends Numerizer(rmap:ReactionMap) {
  val name = "Transition from "+from.name+" to "+to.name
  val maxStep:Int = 10
  var step:Int = 0
  def apply(v:Vertex):Option[Double] = {
    val theta:Double = (Math.PI / 2.0 * step.toDouble / maxStep.toDouble)
    from(v) match {
      case Some(v1) => to(v) match {
        case Some(v2) => Some(v1*Math.cos(theta) + v2*Math.sin(theta))
        case None => None
      }
      case None => None
    }
  }
  def renew():Numerizer = {
    timer.cancel()
    timer.purge()
    new TransitionNumerizer(rmap, from, to, updater, setter)
  }
  val timer:Timer = new Timer()
  timer.schedule(new TimerTask {
    override def run(): Unit = {
      step += 1
      if (step > maxStep) {
        timer.cancel()
        timer.purge()
        setter(to)
      } else {
        updater()
      }
    }
  }, 100, 100)
} 
开发者ID:ReactionMap,项目名称:RMapViewerS,代码行数:42,代码来源:TransitionNumerizer.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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