当前位置: 首页>>代码示例>>Scala>>正文


Scala ChronoUnit类代码示例

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


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

示例1: Player

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

import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Clock, LocalDateTime}
import java.util.{Base64, UUID}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{KeyGenerator, Mac}

@SerialVersionUID(1L)
class Player(val id: UUID, val name: String, val secret: String) extends Serializable {
  override def hashCode = id.hashCode()

  override def equals(other: Any) = other match {
    case that: Player => this.id == that.id
    case _ => false
  }

  override def toString = s"$name ($id)"

  def identity = PlayerIdentity(id, name)

  def isAuthorized(time: LocalDateTime, signature: String): Boolean = {
    val seconds = ChronoUnit.SECONDS.between(time, LocalDateTime.now(Clock.systemUTC()))

    if (seconds < -300 || seconds > 300) {
      false
    } else {
      val secretKeySpec = new SecretKeySpec(secret.getBytes, "HmacSHA256")
      val mac = Mac.getInstance("HmacSHA256")
      mac.init(secretKeySpec)

      val message = id.toString.toLowerCase + "|" + time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
      val hmac = mac.doFinal(message.getBytes("UTF-8"))

      val encoded = Base64.getEncoder.encodeToString(hmac)

      encoded.equalsIgnoreCase(signature)
    }
  }
}

object Player {
  def apply(name: String) = new Player(UUID.randomUUID(), name, generateKey)

  def apply(id: UUID, name: String) = new Player(id, name, generateKey)

  private def generateKey: String = {
    val keyGenerator: KeyGenerator = KeyGenerator.getInstance("HmacSHA256")
    Base64.getEncoder.encodeToString(keyGenerator.generateKey().getEncoded)
  }

  def apply(id: UUID, name: String, secret: String) = new Player(id, name, secret)

  def apply(identity: PlayerIdentity) = new Player(identity.id, identity.name, generateKey)

  def apply(identity: PlayerIdentity, secret: String) = new Player(identity.id, identity.name, secret)
}

case class PlayerIdentity(id: UUID, name: String) 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:61,代码来源:Player.scala

示例2: SimpleCacheApi

//设置package包名称以及导入依赖的类
package au.id.tmm.senatedb.api.integrationtest

import java.time.Instant
import java.time.temporal.ChronoUnit

import play.api.cache.SyncCacheApi

import scala.collection.concurrent.TrieMap
import scala.concurrent.duration.Duration


class SimpleCacheApi extends SyncCacheApi {

  private val map = new TrieMap[String, (Instant, Any)]()

  override def set(key: String, value: Any, expiration: Duration): Unit = {
    val expiryTime = {
      if (expiration == Duration.Inf) {
        Instant.MAX
      } else {
        Instant.now().plus(expiration.toMillis, ChronoUnit.MILLIS)
      }
    }

    map.update(key, (expiryTime, value))
  }

  override def remove(key: String): Unit = {
    map.remove(key)
  }

  override def getOrElseUpdate[A](key: String, expiration: Duration)(orElse: => A)(implicit evidence$1: ClassManifest[A]): A = {
    val existingValue = get(key)

    if (existingValue.isEmpty) {
      set(key, orElse, expiration)
      orElse
    } else {
      existingValue.get
    }
  }

  override def get[T](key: String)(implicit evidence$2: ClassManifest[T]): Option[T] = {
    map.get(key)
      .flatMap { case (expiryTime, value) =>

        if (expiryTime.isAfter(Instant.now())) {
          remove(key)
          None
        } else {
          Some(value)
        }
      }
      .map(_.asInstanceOf[T])
  }
} 
开发者ID:tmccarthy,项目名称:SenateDB,代码行数:57,代码来源:SimpleCacheApi.scala

示例3: ItemCreationActor

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

import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.UUID

import akka.actor.Actor
import com.google.inject.{Inject, Singleton}
import play.api.Logger
import services.Item

@Singleton
class ItemCreationActor @Inject()(cache: StringCache) extends Actor {
  val logger = Logger(this.getClass)

  override def receive: Receive = {
    case "createItem" => createItem()
  }

  def createItem(): Unit = {
    logger.info(s"Creating up cache ($cache)")
    cache.peekLast.fold({
      logger.info(s"No items found, creating one.")
      cache.pushLast(Item(UUID.randomUUID().toString, Instant.now().plus(10, ChronoUnit.SECONDS)))
    }) {
      item =>
        if (item.expiration.minus(3, ChronoUnit.SECONDS).isBefore(Instant.now())) {
          logger.info(s"Last item is about to expire, creating new one.")
          cache.pushLast(Item(UUID.randomUUID().toString, Instant.now().plus(10, ChronoUnit.SECONDS)))
        }
    }
  }
} 
开发者ID:obszczymucha,项目名称:play-scala-fifo-queue,代码行数:34,代码来源:ItemCreationActor.scala

示例4: EmployeeStat

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

import java.time.LocalDate
import java.time.temporal.ChronoUnit
import javax.inject.Inject

import services.MoyskladAPI
import services.moysklad.documents.{RetailDemand, RetailDemandRequest}
import services.moysklad.entity.Employee
import services.moysklad.registry.{EmployeeRegistry, ProductRegistry}

import scala.concurrent.{ExecutionContext, Future}

case class EmployeeStat(employee: Employee, avgQuantity: Double, avgSum: Int, totalSales: Int, totalSum: Int)

class EmployeePerformance @Inject()(moyskladApi: MoyskladAPI, employeeRegistry: EmployeeRegistry)(implicit ec: ExecutionContext) {

  final val reportPeriod = 14

  def buildReport(): Future[Seq[EmployeeStat]] = {
    moyskladApi.getRetailDemand(new RetailDemandRequest(LocalDate.now().minus(reportPeriod, ChronoUnit.DAYS))) map { response =>
      val byEmployee = response.rows groupBy (_.owner.meta.href)
      byEmployee.mapValues(employeeSales2Stat).toSeq.map { t =>
        EmployeeStat(employeeRegistry(t._1), t._2._1, t._2._2, t._2._3, t._2._4)
      }
    }
  }

  protected def employeeSales2Stat(s: Seq[RetailDemand]) : (Double, Int, Int, Int) = {
    val total = s.size
    val bottles = s.foldLeft(0)(_ + _.positions.rows.foldLeft(0)(_ + _.quantity))
    val sum = s.foldLeft(0)(_ + _.sum)
    val avgBottles = bottles.toDouble / total.toDouble
    val avgSum = sum / total
    (avgBottles, avgSum, total, sum)
  }
} 
开发者ID:SeriousDron,项目名称:moysklad-reports,代码行数:38,代码来源:EmployeePerformance.scala

示例5: DurationOperations

//设置package包名称以及导入依赖的类
package io.clouderite.commons.scala.berries.time

import java.time.Duration
import java.time.temporal.{ChronoUnit, TemporalAmount}

import scala.concurrent.duration.FiniteDuration

class DurationOperations(finiteDuration: FiniteDuration) {
}

object DurationOperations {
  implicit def toDurationOperations(finiteDuration: FiniteDuration): DurationOperations =
    new DurationOperations(finiteDuration)

  implicit def toTemporalAmount(finiteDuration: FiniteDuration): TemporalAmount = {
    val value = finiteDuration.toMillis
    Duration.of(value, ChronoUnit.MILLIS)
  }
} 
开发者ID:clouderite,项目名称:scala-berries,代码行数:20,代码来源:DurationOperations.scala

示例6: User

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

import java.time.temporal.ChronoUnit
import java.time.{ZoneOffset, ZonedDateTime}
import java.util.{Date, UUID}

import com.datastax.driver.core.utils.UUIDs
import models.Language.Language
import models.Task.yearAsOfJan1


case class User(name: String, password: String, timeuuid: UUID = UUIDs.timeBased())

case class Task(year: Date, lang: Language, timeuuid: UUID, name: String, description: String,
                solutionTemplate: String, referenceSolution: String, suite: String, solutionTrait: String)

object Task {
  val now = 0

  def yearAsOfJan1(ago: Int = now) =
    Date.from(ZonedDateTime.now(ZoneOffset.UTC)
      .truncatedTo(ChronoUnit.DAYS)
      .withDayOfMonth(1).withMonth(1)
      .minusYears(ago).toInstant)
}

case class NewTask(lang: Language, name: String, description: String, solutionTemplate: String,
                   referenceSolution: String, suite: String, solutionTrait: String, year: Date = yearAsOfJan1(),
                   timeuuid: UUID = UUIDs.timeBased())

object Language extends Enumeration {
  type Language = Value

  val scalaLang = Value
} 
开发者ID:DmytroOrlov,项目名称:devgym,代码行数:36,代码来源:Model.scala

示例7: WateringHelloListener

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

import java.time.temporal.ChronoUnit
import java.time.{Clock, Duration}

import akka.actor.Actor
import mqtt.MqttListenerMessage.{ConsumeMessage, Ping}
import play.api.Logger


class WateringHelloListener(wateringCommander: WateringCommander, clock: Clock) extends Actor {
  val topic = "home/watering/ibisek/hello".r

  override def receive(): Receive = {
    case Ping => ()
    case ConsumeMessage(receivedTopic: String, _: String) => receivedTopic match {
      case topic() =>
        Logger.info("Ibisek watering says hello")
        val wc = WateringCommand(Set(
          TimeCommand(clock.instant()),
          HumidityMeasuringDelay(Duration.of(5, ChronoUnit.SECONDS)),
          HumidityMeasurePowerDelay(Duration.of(100, ChronoUnit.MILLIS)),
          HumidityBaseline(150),
          HumidityMeasureBufferSize(13),
          WateringPause(Duration.of(15, ChronoUnit.MINUTES))
        ))
        wateringCommander.sendCommand(wc)
      case _ => {}
    }
  }
} 
开发者ID:vavravl1,项目名称:home_center,代码行数:32,代码来源:WateringHelloListener.scala

示例8: TimeUtil

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

import java.time._
import java.time.temporal.{ChronoUnit, TemporalUnit, WeekFields}
import java.util.Locale

object TimeUtil {
  private val weekField = WeekFields.of(Locale.getDefault).dayOfWeek()

  def now: LocalDateTime = {
    ZonedDateTime.now(ZoneOffset.UTC).toLocalDateTime
  }

  def nowInSeconds: Long = {
    now.toEpochSecond(ZoneOffset.UTC)
  }

  def isExpired(ttl: Long, `unit`: ChronoUnit, startTime: LocalDateTime): Boolean = {
    val expiration = now.minus(ttl, unit)
    startTime.isBefore(expiration)
  }

  def toStartOfDay(date: LocalDate): LocalDateTime = {
    date.atTime(LocalTime.MIDNIGHT)
  }

  def toEndOfDay(date: LocalDate): LocalDateTime = {
    date.atTime(LocalTime.MIDNIGHT).plusDays(1).minusNanos(1)
  }

  def toTime(sec: Double): String = {
    val hours = sec.toInt / 3600
    val minutes = sec.toInt / 60
    val seconds = (sec % 60).toInt

    def pad(value: Int): String = {
      f"${value}%02d"
    }

    s"${pad(hours)}:${pad(minutes)}:${pad(seconds)}"
  }
} 
开发者ID:crocker,项目名称:temporal-util,代码行数:43,代码来源:TimeUtil.scala

示例9: Middleware

//设置package包名称以及导入依赖的类
package net.andimiller
package http4s
package cache

import java.time.{ZoneOffset, ZonedDateTime}
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit

import org.http4s._
import org.http4s.util.CaseInsensitiveString

import scala.concurrent.duration._
import scala.util.Try
import scalaz.Kleisli
import scalaz.concurrent.Task
import scalaz.stream.Process

object Middleware {
  import KleisliMemo._
  import KleisliCache._

  type HttpMiddleware = Kleisli[Task, Request, Response] => Kleisli[Task, Request, Response]

  val memoMiddleware = new HttpMiddleware {
    override def apply(v1: Service[Request, Response]): Service[Request, Response] =
      v1.concurrentlyMemoize
  }

  val httpDateFormat =
    DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneOffset.UTC)

  def getCacheDuration(r: Response): FiniteDuration = {
    {
      for {
        now            <- r.headers.get(CaseInsensitiveString("date"))
        expires        <- r.headers.get(CaseInsensitiveString("expires"))
        nowInstant     <- Try(ZonedDateTime.parse(now.value, httpDateFormat)).toOption.map(_.toInstant)
        expiresInstant <- Try(ZonedDateTime.parse(expires.value, httpDateFormat)).toOption.map(_.toInstant)
      } yield ChronoUnit.SECONDS.between(nowInstant, expiresInstant).seconds
    }.filter(_.length > 0).getOrElse(Duration.Zero)
  }

  def cacheMiddleware(methods: List[Method] = Method.registered.toList) = new HttpMiddleware {
    override def apply(v1: Service[Request, Response]): Service[Request, Response] = {
      val cached = v1.map { r =>
        val body = r.body.runLog.unsafePerformSync
        ((r, body), getCacheDuration(r))
      }.concurrentlyCacheWithExpiringMap
      HttpService {
        case r if methods.contains(r.method) =>
          cached(r).map {
            case (resp, body) =>
              resp.copy(body = Process.emitAll(body))
          }
        case r =>
          v1(r)
      }
    }
  }

} 
开发者ID:andimiller,项目名称:http4s-cache,代码行数:62,代码来源:Middleware.scala

示例10: TaskAttemptFactory

//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.specutil

import com.pagerduty.scheduler.datetimehelpers._
import com.pagerduty.scheduler.model._
import java.time.temporal.ChronoUnit
import java.time.Instant
import scala.concurrent.duration._

object TaskAttemptFactory {

  def makeTaskAttempt(attemptNumber: Int, taskResult: CompletionResult) = {
    val now = Instant.now().truncatedTo(ChronoUnit.MILLIS)
    val hadException = taskResult match {
      case CompletionResult.Success => false
      case _ => true
    }
    TaskAttempt(
      attemptNumber,
      startedAt = now - 100.millis,
      finishedAt = now - 50.millis,
      taskResult,
      taskResultUpdatedAt = now,
      exceptionClass = if (hadException) Some("YourTaskFailedException") else None,
      exceptionMessage = if (hadException) Some("Something went wrong.") else None,
      exceptionStackTrace = if (hadException) Some("com.pagerduty.app.YourTask.run") else None
    )
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:29,代码来源:TaskAttemptFactory.scala

示例11: DropTaskSpec

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

import com.pagerduty.scheduler.model.Task
import java.time.Instant
import java.time.temporal.ChronoUnit
import org.scalatest.BeforeAndAfter
import org.scalatest.concurrent.Eventually
import org.scalatest.time.{Seconds, Span}
import scala.concurrent.Await
import scala.concurrent.duration._


class DropTaskSpec extends SchedulerIntegrationSpecBase with BeforeAndAfter with Eventually {
  override implicit val patienceConfig = PatienceConfig(timeout = scaled(Span(40, Seconds)))

  var scheduler: TestScheduler = null

  before {
    scheduler = new TestScheduler()
  }

  after {
    scheduler.shutdown()
  }

  "Scheduler should" - {
    "be able to drop stuck tasks" in {
      val orderingId = "orderingId"
      val scheduledTime = Instant.now().truncatedTo(ChronoUnit.MILLIS)
      val stuckTask = new Task(orderingId, scheduledTime, "01", Map("throw!" -> "stuck task"))
      val goodTask = new Task(orderingId, scheduledTime, "02", Map("key" -> "good task"))
      scheduler.scheduleTask(stuckTask)
      scheduler.scheduleTask(goodTask)

      val adminService = scheduler.actualScheduler.adminService

      // Wait for stuckTask to run & fail
      eventually { scheduler.oopsedTasks.size should be > 0 }
      // Wait for Cassandra update to finish to avoid a write race with dropTask.
      eventually {
        val adminTask = Await.result(adminService.fetchTaskWithDetails(stuckTask.taskKey), Duration.Inf)
        adminTask.numberOfAttempts.getOrElse(0) should equal(1)
      }
      // Make sure we haven't taken too long!
      scheduler.executedTasks should not contain (goodTask)
      // Drop the task
      Await.result(adminService.dropTask(stuckTask.taskKey), Duration.Inf)
      // Once stuckTask is dropped, goodTask should be able to run
      eventually { scheduler.executedTasks should contain(goodTask) }
    }
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:53,代码来源:DropTaskSpec.scala

示例12: SchedulerIntegrationWhiteboxSpec

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

import com.pagerduty.metrics.NullMetrics
import com.pagerduty.scheduler.akka.SchedulingSystem
import com.pagerduty.scheduler.datetimehelpers._
import com.pagerduty.scheduler.model.Task
import com.pagerduty.scheduler.model.Task.PartitionId
import java.time.temporal.ChronoUnit
import java.time.Instant
import org.scalamock.scalatest.PathMockFactory
import org.scalatest.BeforeAndAfter
import scala.concurrent.duration._

class SchedulerIntegrationWhiteboxSpec extends SchedulerIntegrationSpecBase with BeforeAndAfter with PathMockFactory {
  after {
    dropAndLoadCassSchema()
  }

  "Scheduler Whitebox Integration Tests" - {
    val taskRunner = (task: Task) => {}
    val executorFactory = SchedulerIntegrationSpecBase.simpleTestExecutorFactory(taskRunner)
    val logging = stub[Scheduler.Logging]

    "should shut down the entire actor system upon encountering an exception" in {
      val partitionIds = Set[PartitionId](0)
      val schedulingSystem = {
        new SchedulingSystem(config, cluster, keyspace, partitionIds, executorFactory, logging, NullMetrics)
      }
      val scheduledTime = (Instant.now() + 5.seconds).truncatedTo(ChronoUnit.MILLIS)
      val task = new Task("oid1", scheduledTime, "uniq-key-1", Map("k" -> "v"))
      val persistAndScheduleTask = Map[PartitionId, Seq[Task]](partitionIds.head -> Seq(task))
      schedulingSystem.persistAndSchedule(persistAndScheduleTask)

      getSchemaLoader().dropSchema() // This will cause Cassandra error when the task runs.

      // The cassandra error should cause an error to propagate up the actor system.
      // This will activate the supervision strategy and cause the scheduling system to shut down.
      schedulingSystem.getActorSystem().awaitTermination(1.minute)
    }
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:42,代码来源:SchedulerIntegrationWhiteboxSpec.scala

示例13: TaskFactory

//设置package包名称以及导入依赖的类
package com.pagerduty.scheduler.specutil

import com.pagerduty.eris.TimeUuid
import com.pagerduty.scheduler.datetimehelpers._
import com.pagerduty.scheduler.model.{Task, TaskKey}
import java.time.Instant
import java.time.temporal.ChronoUnit
import scala.concurrent.duration._

object TaskFactory {
  private def timeNowFlooredToMs: Instant = Instant.now().truncatedTo(ChronoUnit.MILLIS)

  def makeTask(scheduledTime: Instant = timeNowFlooredToMs): Task = {
    // for reasons unknown, various tests are dependent on TimeUuid being used here :-(
    Task(
      orderingId = TimeUuid().toString,
      scheduledTime = scheduledTime,
      uniquenessKey = TimeUuid().toString,
      taskData = Map("taskId" -> TimeUuid().toString)
    )
  }

  def makeTaskKey(scheduledTime: Instant = timeNowFlooredToMs): TaskKey = {
    makeTask(scheduledTime).taskKey
  }

  def makeTasks(
      count: Int,
      scheduledTime: Instant = timeNowFlooredToMs,
      spacing: Duration = 0.seconds
    ): IndexedSeq[Task] = {
    for (i <- 0 until count) yield TaskFactory.makeTask(scheduledTime + (spacing * i))
  }

  def makeTasksInConsecutiveBuckets(rowTimeBucketDuration: Duration): (Seq[Task], Seq[Task]) = {
    val currentTimeBucket = Instant.now()
    val nextTimeBucket = currentTimeBucket + rowTimeBucketDuration
    val tasks = for (i <- 0 to 5) yield TaskFactory.makeTask()
    val currentBucketTasks = tasks.map(_.copy(scheduledTime = currentTimeBucket))
    val nextBucketTasks = tasks.map(_.copy(scheduledTime = nextTimeBucket))
    (currentBucketTasks, nextBucketTasks)
  }
} 
开发者ID:PagerDuty,项目名称:scheduler,代码行数:44,代码来源:TaskFactory.scala

示例14: DateUtils

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

import java.time.LocalDate
import java.time.ZoneId
import java.time.temporal.ChronoUnit

object DateUtils {
  def dates(dateStart: String, dateEnd: String): Seq[LocalDate] = {
    val start = LocalDate.parse(dateStart)
    val days = ChronoUnit.DAYS.between(start, LocalDate.parse(dateEnd)).toInt
    for (dayIndex <- 0 to days) yield start.plusDays(dayIndex)
  }

  def parseZone(rawZone: String): ZoneId = {
    ZoneId.of(rawZone match {
      case "ET" => "America/New_York"
      case unknown => unknown
    })
  }
} 
开发者ID:cberes,项目名称:hockey-stats-loader,代码行数:21,代码来源:date_utils.scala

示例15: Common

//设置package包名称以及导入依赖的类
package io.chymyst.benchmark

import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

object Common {
  val warmupTimeMs = 50L

  def elapsed(initTime: LocalDateTime): Long = initTime.until(LocalDateTime.now, ChronoUnit.MILLIS)

  def elapsed(initTime: Long): Long = System.currentTimeMillis() - initTime

  def timeThis(task: => Unit): Long = {
    val initTime = LocalDateTime.now
    task
    elapsed(initTime)
  }

  def timeWithPriming(task: => Unit): Long = {
    task // this is just priming, no measurement

    val result1 = timeThis {
      task
    }
    val result2 = timeThis {
      task
    }
    (result1 + result2 + 1) / 2
  }

  def waitSome(): Unit = Thread.sleep(warmupTimeMs)

} 
开发者ID:Chymyst,项目名称:chymyst-core,代码行数:34,代码来源:Common.scala


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