本文整理汇总了Scala中java.util.TimerTask类的典型用法代码示例。如果您正苦于以下问题:Scala TimerTask类的具体用法?Scala TimerTask怎么用?Scala TimerTask使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TimerTask类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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 }
}
}
示例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
}
}
示例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
}
示例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(); () }
}
}
示例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()
}
示例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)
}
}
示例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))
}
}
}
示例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()
}
}
示例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
}
}
示例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);
}
}
示例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")
}
示例12: 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)
}
示例13: Timer
//设置package包名称以及导入依赖的类
package tester
import scala.concurrent.{Future, Promise}
import java.util.{Timer => JavaTimer}
import java.util.TimerTask
import scala.util.Try
import java.util.{Timer => JavaTimer}
object Timer {
def completeAfter(duration: Long): Future[Unit] = {
val promise = Promise[Unit]
val javaTimer = new JavaTimer
javaTimer.schedule(
new TimerTask {
override def run() = { promise.complete(Try(Unit)) }
}, duration)
promise.future
}
}
示例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)
}
示例15: Help
//设置package包名称以及导入依赖的类
package wrapper
import java.time._
import java.util.TimerTask
import java.util.Timer;
import scala.collection.immutable.ListMap
object Help {
var TrackMap: Map[String,List[Long]] = Map()
val helpTimer = new Timer()
val helpTask = new HelpTask()
helpTimer.schedule(helpTask, 500, 1000)
def time[T](name: String = "No-Name", a: Instant = Instant.now())(value: T, c: Instant = Instant.now()): T = {
val time = Duration.between(a,c).toMillis
//println(name+": "+(time))
TrackMap = if(TrackMap.contains(name)){
TrackMap + (name -> (time::TrackMap(name)))
} else {
TrackMap + (name -> List(time))
}
//println(TrackMap(name).length)
value
}
def print {
println()
TrackMap = ListMap(TrackMap.toSeq.sortWith(_._1 < _._1):_*)
TrackMap.foreach(kv=>{
println(kv._1+": "+kv._2.length+" runs averaging "+(0.0+kv._2.foldLeft[Long](0)((b,a)=>b+a))/kv._2.length+"ms")
})
TrackMap = Map()
}
}
class HelpTask extends TimerTask {
def run = {
//println("poop")
Help.print
}
}