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

Scala ChronoUnit类代码示例

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

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



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


示例16: S3FileApp

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

import scala.io.Source
import java.time.Period
import java.time.LocalDate
import java.time.temporal.TemporalUnit
import java.time.temporal.ChronoUnit
import java.time.LocalDateTime

object S3FileApp extends App {
  val url1 = "http://prod.publicdata.landregistry.gov.uk.s3-website-eu-west-1.amazonaws.com/pp-monthly-update-new-version.csv"
  val url2 = "http://prod.publicdata.landregistry.gov.uk.s3-website-eu-west-1.amazonaws.com/pp-complete.csv"

  lazy val lines = Source.fromURL(url2).getLines

  val start = LocalDateTime.now
  val count = lines.size
  val end = LocalDateTime.now
  val seconds = ChronoUnit.MILLIS.between(start, end) / 1000.0
  println("\nCount: " + count + " took: " + seconds + "s")
} 
开发者ID:ayubmalik,项目名称:houseprices,代码行数:22,代码来源:S3FileApp.scala


示例17: ZonedDateTimeSyntax

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

import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit

import scala.concurrent.duration._

trait ZonedDateTimeSyntax {

  implicit class ZonedDateTimeSyntax(val zonedDateTime: ZonedDateTime) {
    def minus(zonedDateTimeB: ZonedDateTime): FiniteDuration =
      Duration.apply(ChronoUnit.NANOS.between(zonedDateTimeB, zonedDateTime), NANOSECONDS)

    def durationBetween(zonedDateTimeB: ZonedDateTime): FiniteDuration =
      if(zonedDateTimeB.isBefore(zonedDateTime))
        minus(zonedDateTimeB)
      else
        zonedDateTimeB.minus(zonedDateTime)

    def minus(duration: FiniteDuration): ZonedDateTime =
      zonedDateTime.minusSeconds(duration.toSeconds)

    def plus(duration: FiniteDuration): ZonedDateTime =
      zonedDateTime.plusSeconds(duration.toSeconds)

    def isBetween(timeA: ZonedDateTime, timeB: ZonedDateTime): Boolean =
      ( (zonedDateTime.isAfter(timeA) || zonedDateTime.isEqual(timeA)) && (zonedDateTime.isBefore(timeB) || zonedDateTime.isEqual(timeA)) ) ||
        ( (zonedDateTime.isAfter(timeB) || zonedDateTime.isEqual(timeB)) && (zonedDateTime.isBefore(timeA) || zonedDateTime.isEqual(timeA)) )

    def isBetweenExclusive(timeA: ZonedDateTime, timeB: ZonedDateTime): Boolean =
      (zonedDateTime.isAfter(timeA)  && zonedDateTime.isBefore(timeB)) ||
        (zonedDateTime.isAfter(timeB) && zonedDateTime.isBefore(timeA))
  }
}

object zonedDateTime extends ZonedDateTimeSyntax 
开发者ID:ahamdy88,项目名称:JobForce,代码行数:37,代码来源:zonedDateTime.scala


示例18: JobDueCheckerTest

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

import java.time.temporal.ChronoUnit
import java.time.{ZoneId, ZonedDateTime}

import scala.concurrent.duration._
import com.cronutils.model.CronType
import io.ahamdy.taskforce.domain.JobSchedule
import io.ahamdy.taskforce.scheduling.CronLine
import io.ahamdy.taskforce.syntax.zonedDateTime._
import io.ahamdy.taskforce.testing.syntax.either._
import io.ahamdy.taskforce.testing.StandardSpec


class JobDueCheckerTest extends StandardSpec {
  val now: ZonedDateTime = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC")).truncatedTo(ChronoUnit.DAYS).plusMinutes(30)
  "JobDueChecker" should {
    "isDue should return true only if job next execution time is within startTimeWindow" in {
      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("0 * * * * ?", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 2.minute),
        now = now,
        actualLastTimeRun = now.minus(2.minutes)) must beTrue

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("*/2 * * * *", CronType.UNIX, ZoneId.of("UTC")).getRight, 3.minute),
        now = now,
        actualLastTimeRun = now.minus(2.minutes)) must beTrue

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("* 0 0/1 ? * * *", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 2.minute),
        now = now,
        actualLastTimeRun = now.minus(2.minutes)) must beFalse

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("* 20 0 ? * * *", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 11.minute),
        now = now,
        actualLastTimeRun = now.minus(1.day)) must beTrue

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("* 20 0 ? * * *", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 11.minute),
        now = now,
        actualLastTimeRun = now.minus(10.day)) must beTrue

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("* 20 1 ? * * *", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 11.minute),
        now = now,
        actualLastTimeRun = now.minus(10.day)) must beFalse

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("* 20 0 ? * * *", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 11.minute),
        now = now,
        actualLastTimeRun = now.minus(10.minute)) must beTrue

      JobDueChecker.isDue(
        JobSchedule(CronLine.parse("* 20 0 ? * * *", CronType.QUARTZ, ZoneId.of("UTC")).getRight, 9.minute),
        now = now,
        actualLastTimeRun = now.minus(10.minute)) must beFalse
    }
  }
} 
开发者ID:ahamdy88,项目名称:JobForce,代码行数:61,代码来源:JobDueCheckerTest.scala


示例19: LogProcessorProps

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

import java.time.temporal.ChronoUnit
import java.time.{ZoneId, Instant, ZonedDateTime}

import model.Song
import org.scalacheck.{Arbitrary, Gen, Prop, Properties}

class LogProcessorProps extends Properties("LogProcessor") {

  val songGen: Gen[Song] =
    for {
      trackId <- Gen.oneOf(None, Some("Track"));
      trackName <- Gen.alphaStr;
      artistId <- Gen.oneOf(None, Some("Artist"));
      artistName <- Gen.alphaStr
    } yield Song(trackId, trackName, artistId, artistName)

  def songLongTupleGen(timestampGen: Gen[Long]): Gen[(Song, Long)] =
    for {
      song <- songGen;
      frequency <- timestampGen
    } yield (song, frequency)

  property("splitIntoSessions shouldn't loose songs") =
    Prop.forAll(Gen.listOf(songLongTupleGen(Gen.chooseNum(0L, Int.MaxValue.toLong))))
    { (input: Seq[(Song, Long)]) =>
      LogProcessor.splitIntoSessions(input.iterator).map(_.size).sum == input.size
    }

  property("splitIntoSessions should create only one Seq if all are less than 20 minutes apart ") =
    Prop.forAll(Gen.listOf(songLongTupleGen(Gen.chooseNum(0L, 19*60L))))
    { (input: Seq[(Song, Long)]) =>
      LogProcessor.splitIntoSessions(input.iterator).size == 1
    }

  val zoneDateTimeGen: Gen[ZonedDateTime] = for {
    timestamp <- Arbitrary.arbitrary[Long]
  } yield ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault())

  property("minutesBetween") = Prop.forAll(zoneDateTimeGen, zoneDateTimeGen) {(d1: ZonedDateTime, d2: ZonedDateTime) =>
    LogProcessor.minutesBetween(d1.toEpochSecond, d2.toEpochSecond) == ChronoUnit.MINUTES.between(d1, d2)
  }

} 
开发者ID:simonsaffer,项目名称:loganalysis,代码行数:46,代码来源:LogProcessorProps.scala


示例20: InMemoryStoreSpec

//设置package包名称以及导入依赖的类
package com.criteo.slab.lib

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

import org.scalatest.{FlatSpec, Matchers}
import org.slf4j.LoggerFactory

import scala.collection.concurrent.TrieMap

class InMemoryStoreSpec extends FlatSpec with Matchers {
  val logger = LoggerFactory.getLogger(this.getClass)
  "Cleaner" should "remove expired entries" in {
    val cache = TrieMap.empty[(String, Long), Any]
    val cleaner = InMemoryStore.createCleaner(cache, 1, logger)

    cache += ("a", Instant.now.minus(2, ChronoUnit.DAYS).toEpochMilli) -> 1
    cache += ("b", Instant.now.minus(1, ChronoUnit.DAYS).toEpochMilli) -> 2
    cache += ("c", Instant.now.toEpochMilli) -> 3
    cleaner.run()
    cache.size shouldBe 1
    cache.head._1._1 shouldBe "c"
  }

} 
开发者ID:criteo,项目名称:slab,代码行数:26,代码来源:InMemoryStoreSpec.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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