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


Scala Instant类代码示例

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


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

示例1: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:sarathraj-coder,项目名称:play2_6curd_rest,代码行数:27,代码来源:ApplicationTimer.scala

示例2: Session

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.googlecloud.pubsub

import java.security.PrivateKey
import java.time.Instant

import akka.actor.ActorSystem
import akka.stream.Materializer

import scala.concurrent.Future

@akka.annotation.InternalApi
private[pubsub] class Session(clientEmail: String, privateKey: PrivateKey) {
  protected var maybeAccessToken: Option[Future[AccessTokenExpiry]] = None
  protected def now = Instant.now()
  protected val httpApi: HttpApi = HttpApi

  private def getNewToken()(implicit as: ActorSystem, materializer: Materializer): Future[AccessTokenExpiry] = {
    val accessToken = httpApi.getAccessToken(clientEmail = clientEmail, privateKey = privateKey, when = now)
    maybeAccessToken = Some(accessToken)
    accessToken
  }

  private def expiresSoon(g: AccessTokenExpiry): Boolean =
    g.expiresAt < (now.getEpochSecond + 60)

  def getToken()(implicit as: ActorSystem, materializer: Materializer): Future[String] = {
    import materializer.executionContext
    maybeAccessToken
      .getOrElse(getNewToken())
      .flatMap { result =>
        if (expiresSoon(result)) {
          getNewToken()
        } else {
          Future.successful(result)
        }
      }
      .map(_.accessToken)
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:40,代码来源:Session.scala

示例3: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:Tkanbara,项目名称:bookmarkShare,代码行数:27,代码来源:ApplicationTimer.scala

示例4: E2ESpec

//设置package包名称以及导入依赖的类
package com.hivehome.kafka.connect.sqs

import java.time.Instant

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

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future


class E2ESpec extends FunSuite with Matchers with SQSSupport {
  val logger = LoggerFactory.getLogger(getClass.getName)
  private val KafkaTopic: String = "connect-test"
  override val queueName = "test-sqs" // kafka connect should be setup with this SQS
  queueUrl = sqs.getQueueUrl(queueName).getQueueUrl

  private val props = Map(
    "bootstrap.servers" -> sys.env.getOrElse("KAFKA", "localhost:9092"),
    "schema.registry.url" -> sys.env.getOrElse("SCHEMA_REGISTRY", "http://localhost:8081"))

  val consumer = KafkaAvroConsumer[String, String](props, topicName = KafkaTopic)

  // Test is ignored because it does not run without dependent services
  ignore("should route message SQS -> Kafka") {
    Future {
      // sleep is required so that the message to SQS
      // is sent after the consumer is listening on the kafka topic
      Thread.sleep(500)
      logger.debug("sending message..")
      sendMessage(Instant.now().toString)
      logger.debug("sent message..")
    }

    val msgs = consumer.poll(1, accept = _ => true)

    msgs should have size 1
  }
} 
开发者ID:ConnectedHomes,项目名称:sqs-kafka-connect,代码行数:40,代码来源:E2ESpec.scala

示例5: ScheduleParser

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

import java.time.{Clock, Instant}
import javax.inject._

import akka.actor.{ActorRef, ActorSystem, Cancellable}
import play.api.Logger
import play.api._
import play.api.inject.ApplicationLifecycle

import scala.concurrent.Future
import logic.actors.schedule.CheckScheduleDateActor._

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global


@Singleton
class ScheduleParser @Inject()(clock: Clock, appLifecycle: ApplicationLifecycle,system: ActorSystem , env: Environment,
                               @Named("checkSchedule") checkScheduleDateActor: ActorRef) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  private var cancellable1:Cancellable = null



  Logger.info(s"ScheduleParser: Starting application at ${start}.")

  if(env.mode == Mode.Prod || env.mode == Mode.Dev) {
    cancellable1 = system.scheduler.schedule(2 second, 1 day ,checkScheduleDateActor , CheckScheduleDate)
  }

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ScheduleParser: Stopping application at ${clock.instant} after ${runningTime}s.")
    if(cancellable1 != null){
      cancellable1.cancel()
    }
    Future.successful(())
  }

} 
开发者ID:P1tt187,项目名称:spirit-play,代码行数:48,代码来源:ScheduleParser.scala

示例6: Marshalling

//设置package包名称以及导入依赖的类
package akka.stream.alpakka.s3.impl

import java.time.Instant

import akka.http.scaladsl.marshallers.xml.ScalaXmlSupport
import akka.http.scaladsl.model.{ContentTypes, HttpCharsets, MediaTypes}
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.stream.alpakka.s3.scaladsl.ListBucketResultContents

import scala.xml.NodeSeq

private[alpakka] object Marshalling {
  import ScalaXmlSupport._

  implicit val multipartUploadUnmarshaller: FromEntityUnmarshaller[MultipartUpload] = {
    nodeSeqUnmarshaller(ContentTypes.`application/octet-stream`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        MultipartUpload(S3Location((x \ "Bucket").text, (x \ "Key").text), (x \ "UploadId").text)
    }
  }

  implicit val completeMultipartUploadResultUnmarshaller: FromEntityUnmarshaller[CompleteMultipartUploadResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`) map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        CompleteMultipartUploadResult(
          (x \ "Location").text,
          (x \ "Bucket").text,
          (x \ "Key").text,
          (x \ "ETag").text.drop(1).dropRight(1)
        )
    }
  }

  val isTruncated = "IsTruncated"
  val continuationToken = "NextContinuationToken"

  implicit val listBucketResultUnmarshaller: FromEntityUnmarshaller[ListBucketResult] = {
    nodeSeqUnmarshaller(MediaTypes.`application/xml` withCharset HttpCharsets.`UTF-8`).map {
      case NodeSeq.Empty => throw Unmarshaller.NoContentException
      case x =>
        ListBucketResult(
          (x \ isTruncated).text == "true",
          Some(x \ continuationToken).filter(_.nonEmpty).map(_.text),
          (x \\ "Contents").map { c =>
            ListBucketResultContents(
              (x \ "Name").text,
              (c \ "Key").text,
              (c \ "ETag").text.drop(1).dropRight(1),
              (c \ "Size").text.toLong,
              Instant.parse((c \ "LastModified").text),
              (c \ "StorageClass").text
            )
          }
        )
    }
  }
} 
开发者ID:akka,项目名称:alpakka,代码行数:60,代码来源:Marshalling.scala

示例7: ApplicationTimer

//设置package包名称以及导入依赖的类
@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at ${start}.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
}
*/ 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:19,代码来源:ApplicationTimer.scala

示例8: NettyBench

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

import java.time.Duration
import java.time.Instant
import java.util.concurrent.Executors

import com.naoh.beef.Client
import com.naoh.beef.Server
import com.naoh.beef.proto.echo.EchoGrpc
import com.naoh.beef.proto.echo.EchoGrpc.EchoBlockingStub
import com.naoh.beef.proto.echo.EchoReq
import io.grpc.CallOptions
import io.grpc.ManagedChannelBuilder
import io.grpc.ServerBuilder
import io.grpc.netty.NettyChannelBuilder
import io.grpc.netty.NettyServerBuilder

import scala.concurrent.ExecutionContext
import scala.util.Try


class NettyBench {

  val serverCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val clientCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val server = NettyServerBuilder.forPort(8899).addService(EchoGrpc.bindService(EchoImpl, serverCtx)).build().start()
  val ch = NettyChannelBuilder.forAddress("localhost", 8899).usePlaintext(true).build()
  val client = new EchoBlockingStub(ch, CallOptions.DEFAULT.withExecutor(clientCtx))
  Thread.sleep(1000)

  val base = Instant.now
  Iterator.range(0, 3000).toSeq.toParArray.foreach { _ => Try(client.retEcho(EchoReq("12"))); print(".") }
  val record = Duration.between(base, Instant.now())

  println(s"\n\nDuration $record \n")

  Thread.sleep(2000)
  clientCtx.shutdown()
  serverCtx.shutdown()
  server.shutdown()
  ch.shutdown()
} 
开发者ID:naoh87,项目名称:grpc-scala-experiment,代码行数:43,代码来源:NettyBench.scala

示例9: BeefTest

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

import java.time.Duration
import java.time.Instant
import java.util.concurrent.Executors

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.naoh.beef.Auth
import com.naoh.beef.Beef
import com.naoh.beef.Client
import com.naoh.beef.Region
import com.naoh.beef.Server
import com.naoh.beef.proto.echo.EchoGrpc
import com.naoh.beef.proto.echo.EchoReq
import com.typesafe.config.ConfigFactory

import scala.concurrent.Await
import scala.concurrent.ExecutionContext
import scala.util.Try


class BeefTest {

  val serverSystem = ActorSystem("MyActorSystem", ConfigFactory.parseResources("server.conf").resolve())
  val clientSystem = ActorSystem("MyActorSystem", ConfigFactory.parseResources("client.conf").resolve())
  Cluster(serverSystem).join(Cluster(serverSystem).selfAddress)
  Cluster(clientSystem).join(Cluster(serverSystem).selfAddress)
  val serverCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val clientCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))

  val region = Region("rg")
  val auth = Auth("au")

  Thread.sleep(1000)

  Beef(serverSystem)(
    Server(region)
      << EchoGrpc.bindService(EchoImpl, serverCtx))
  Thread.sleep(1000)

  val builder = Client(region, auth, clientCtx) connect Beef(clientSystem)
  val client = builder.build(new EchoGrpc.EchoBlockingStub(_, _))
  Thread.sleep(1000)

  val base = Instant.now
  Iterator.range(0, 3000).toSeq.toParArray.foreach{_ => Try(client.retEcho(EchoReq("12"))); print(".")}
  val record = Duration.between(base, Instant.now())

  println(s"\n\nDuration $record \n")

  Thread.sleep(2000)
  clientCtx.shutdown()
  serverCtx.shutdown()
  clientSystem.shutdown()
  serverSystem.shutdown()
} 
开发者ID:naoh87,项目名称:grpc-scala-experiment,代码行数:58,代码来源:BeefTest.scala

示例10: string

//设置package包名称以及导入依赖的类
package cz.alenkacz.db.postgresscala

import java.net.InetAddress
import java.sql.Time
import java.time.Instant
import java.util.UUID

trait DbValue {
  def string: String
  def stringOpt: Option[String]
  def strings: Seq[String]
  def int: Int
  def intOpt: Option[Int]
  def ints: Seq[Int]
  def bigInt: BigInt
  def bigIntOpt: Option[BigInt]
  def bigInts: Seq[BigInt]
  def double: Double
  def doubleOpt: Option[Double]
  def doubles: Seq[Double]
  def float: Float
  def floatOpt: Option[Float]
  def floats: Seq[Float]
  def long: Long
  def longOpt: Option[Long]
  def longs: Seq[Long]
  def bool: Boolean
  def boolOpt: Option[Boolean]
  def bools: Seq[Boolean]
  def short: Short
  def shortOpt: Option[Short]
  def shorts: Seq[Short]
  def inetAddress: InetAddress
  def inetAddresses: Seq[InetAddress]
  def inetAddressOpt: Option[InetAddress]
  def uuid: UUID
  def uuids: Seq[UUID]
  def uuidOpt: Option[UUID]
  def instant: Instant
  def instantOpt: Option[Instant]
  def time: Time
  def timeOpt: Option[Time]
  def bytes: Seq[Byte]
  def bytesOpt: Option[Seq[Byte]]
  def any: Any
} 
开发者ID:alenkacz,项目名称:postgres-scala,代码行数:47,代码来源:DbValue.scala

示例11: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._

import play.api.Logger
import play.api.inject.ApplicationLifecycle

import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at $start.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecycle object. The code inside the stop hook will
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:aNkM,项目名称:homework-pokemon,代码行数:29,代码来源:ApplicationTimer.scala

示例12: timestampToInstant

//设置package包名称以及导入依赖的类
package antikkor.example.blog

import java.time.Instant

import akka.AdapterActor
import cats.instances.option._
import fluent._

trait BlogAdapterActor extends AdapterActor {

  implicit def timestampToInstant(timestamp: Long): Instant = Instant.ofEpochMilli(timestamp)
  implicit def instantToTimestamp(instant: Instant): Long = instant.toEpochMilli

  override def translate: PartialFunction[Any, Any] = {
    case Protocol.AllPosts         => Model.AllPosts
    case message: Protocol.Post    => message.transformTo[Model.Publish]
    case message: Model.Published  => message.transformTo[Protocol.Published.type]
    case message: Model.Posts      => message.posts.map(_.transformTo[Protocol.Post])
  }

} 
开发者ID:btlines,项目名称:antikkor,代码行数:22,代码来源:BlogAdapterActor.scala

示例13: ApplicationTimer

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

import java.time.{Clock, Instant}
import javax.inject._
import play.api.Logger
import play.api.inject.ApplicationLifecycle
import scala.concurrent.Future


@Singleton
class ApplicationTimer @Inject() (clock: Clock, appLifecycle: ApplicationLifecycle) {

  // This code is called when the application starts.
  private val start: Instant = clock.instant
  Logger.info(s"ApplicationTimer demo: Starting application at ${start}.")

  // When the application starts, register a stop hook with the
  // ApplicationLifecyle object. The code inside the stop hook wil
  // be run when the application stops.
  appLifecycle.addStopHook { () =>
    val stop: Instant = clock.instant
    val runningTime: Long = stop.getEpochSecond - start.getEpochSecond
    Logger.info(s"ApplicationTimer demo: Stopping application at ${clock.instant} after ${runningTime}s.")
    Future.successful(())
  }
} 
开发者ID:uryyyyyyy,项目名称:adReferenceImplementation,代码行数:27,代码来源:ApplicationTimer.scala

示例14: InfluxQueryBuilder

//设置package包名称以及导入依赖的类
package io.waylay.influxdb.query

import java.time.Instant

import io.waylay.influxdb.{SharedProtocol, InfluxDB}
import io.waylay.influxdb.InfluxDB._

object InfluxQueryBuilder extends SharedProtocol{


  sealed trait IInstant
  object Now extends IInstant
  case class Exact(instant: Instant) extends IInstant
  case class RelativeTo(to: IInstant = Now, timeToGoBack: Duration) extends IInstant



  
  private def escapeStringLiteral(tag: String) = {
    "'" + tag.replace("'","\'") + "'"
  }



  private def instantToExpression(instant: IInstant):String = instant match {
    case Now => "now()"
    case Exact(inst) => inst.toEpochMilli.toString + "ms" // TODO do we want to go more precise?
    case RelativeTo(to, timeToGoBack) => instantToExpression(to) + " - " + durationLiteral(timeToGoBack)
  }

  private def functionToSelect(iFunction: IFunction):String = iFunction match{
    case Count(Left(field)) => s"""COUNT(${escapeValue(field)})"""
    case Count(Right(func)) => s"""COUNT(${functionToSelect(func)})"""
    case Min(field)         => s"""MIN(${escapeValue(field)})"""
    case Max(field)         => s"""MAX(${escapeValue(field)})"""
    case Mean(field)        => s"""MEAN(${escapeValue(field)})"""
    case Median(field)      => s"""MEDIAN(${escapeValue(field)})"""
    case Distinct(field)    => s"""DISTINCT(${escapeValue(field)})"""
    case Sum(field)         => s"""SUM(${escapeValue(field)})"""
    case Stddev(field)      => s"""STDDEV(${escapeValue(field)})"""
    case Last(field)        => s"""LAST(${escapeValue(field)})"""
    case First(field)       => s"""FIRST(${escapeValue(field)})"""
    case other => throw new RuntimeException("not implemented: " + other.toString)
  }

  private def instantToWhereExpression(interval: Interval): Option[String] = {
    interval match {
      case Interval(None, None) => None
      case Interval(Some(start), None) => Some("time >= " + instantToExpression(start))
      case Interval(None, Some(end)) => Some("time < " + instantToExpression(end))
      case Interval(Some(start), Some(end)) => Some("time >= " + instantToExpression(start) + " AND time < " + instantToExpression(end))
    }
  }
} 
开发者ID:waylayio,项目名称:influxdb-scala,代码行数:55,代码来源:InfluxQueryBuilder.scala

示例15: DoobieHelpers

//设置package包名称以及导入依赖的类
package com.imageintelligence.pix.repository

import java.net.{URL, URLDecoder}
import java.time.Instant

import doobie.imports._

object DoobieHelpers {
  implicit val URLMeta: Meta[URL] =
    Meta[String].nxmap(
      i => new URL(i),
      i => URLDecoder.decode(i.toString, "UTF-8")
    )

  implicit val InstantMeta: Meta[Instant] =
    Meta[java.sql.Timestamp].nxmap(
      i => i.toInstant,
      i => new java.sql.Timestamp(i.toEpochMilli)
    )
} 
开发者ID:ImageIntelligence,项目名称:pix-api,代码行数:21,代码来源:DoobieHelpers.scala


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