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

Scala Duration类代码示例

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

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



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

示例1: FileSourceSpec

//设置package包名称以及导入依赖的类
package knot.core.sources

import java.nio.charset.StandardCharsets.UTF_8
import java.nio.file.Files

import knot.core.collectors.Last
import knot.core.{Knot, Workbench}
import knot.data.ByteNode
import knot.testKit.ThroughParser
import org.scalatest.Matchers._
import org.scalatest.{BeforeAndAfter, FunSpec}

import scala.concurrent.Await
import scala.concurrent.duration.Duration

class FileSourceSpec extends FunSpec with BeforeAndAfter {

  implicit val wb: Workbench = Workbench.on("test")

  private val testText = {
    ("a" * 513) +
      ("b" * 513) +
      ("c" * 513)
  }

  private val testFile = {
    val f = Files.createTempFile("file-source-spec", ".tmp")
    Files.newBufferedWriter(f, UTF_8).append(testText).close()
    f
  }

  private def test(): Seq[String] = {
    var actual = Seq[String]()
    val f = Knot
      .from(FileSource(testFile, 512, 5))
      .to(ThroughParser[ByteNode](e => actual = actual :+ e.utf8String))
      .start(Last[ByteNode]())
    Await.result(f, Duration.Inf)
    actual
  }

  after {
    Files.delete(testFile)
  }

  describe("file source") {
    it("file") {
      val actual = test()
      actual should be(Seq(
        "a" * 512,
        "a" + ("b" * 511),
        "bb" + ("c" * 510),
        "ccc"
      ))
    }
  }

} 
开发者ID:defvar,项目名称:knot,代码行数:59,代码来源:FileSourceSpec.scala


示例2: TestLatch

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

import scala.concurrent.duration.Duration
import akka.actor.ActorSystem
import scala.concurrent.{ Await, CanAwait, Awaitable }
import java.util.concurrent.{ TimeoutException, CountDownLatch, TimeUnit }
import scala.concurrent.duration.FiniteDuration


object TestLatch {
  val DefaultTimeout = Duration(5, TimeUnit.SECONDS)

  def apply(count: Int = 1)(implicit system: ActorSystem) = new TestLatch(count)
}

class TestLatch(count: Int = 1)(implicit system: ActorSystem) extends Awaitable[Unit] {
  private var latch = new CountDownLatch(count)

  def countDown() = latch.countDown()
  def isOpen: Boolean = latch.getCount == 0
  def open() = while (!isOpen) countDown()
  def reset() = latch = new CountDownLatch(count)

  @throws(classOf[TimeoutException])
  def ready(atMost: Duration)(implicit permit: CanAwait) = {
    val waitTime = atMost match {
      case f: FiniteDuration ? f
      case _                 ? throw new IllegalArgumentException("TestLatch does not support waiting for " + atMost)
    }
    val opened = latch.await(waitTime.dilated.toNanos, TimeUnit.NANOSECONDS)
    if (!opened) throw new TimeoutException(
      "Timeout of %s with time factor of %s" format (atMost.toString, TestKitExtension(system).TestTimeFactor))
    this
  }
  @throws(classOf[Exception])
  def result(atMost: Duration)(implicit permit: CanAwait): Unit = {
    ready(atMost)
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:40,代码来源:TestLatch.scala


示例3: gracefulStop

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

import akka.actor._
import akka.util.{ Timeout }
import akka.dispatch.sysmsg.{ Unwatch, Watch }
import scala.concurrent.Future
import scala.concurrent.duration.Duration
import scala.util.Success
import scala.concurrent.duration.FiniteDuration

trait GracefulStopSupport {
  
  def gracefulStop(target: ActorRef, timeout: FiniteDuration, stopMessage: Any = PoisonPill): Future[Boolean] = {
    if (target.isTerminated) Future successful true
    else {
      val internalTarget = target.asInstanceOf[InternalActorRef]
      val ref = PromiseActorRef(internalTarget.provider, Timeout(timeout), targetName = target.toString)
      internalTarget.sendSystemMessage(Watch(internalTarget, ref))
      target.tell(stopMessage, Actor.noSender)
      ref.result.future.transform(
        {
          case Terminated(t) if t.path == target.path ? true
          case _                                      ? { internalTarget.sendSystemMessage(Unwatch(target, ref)); false }
        },
        t ? { internalTarget.sendSystemMessage(Unwatch(target, ref)); t })(ref.internalCallingThreadExecutionContext)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:29,代码来源:GracefulStopSupport.scala


示例4: ReceiveTimeout

//设置package包名称以及导入依赖的类
package akka.actor.dungeon

import ReceiveTimeout.emptyReceiveTimeoutData
import akka.actor.ActorCell
import akka.actor.ActorCell.emptyCancellable
import akka.actor.Cancellable
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration

private[akka] object ReceiveTimeout {
  final val emptyReceiveTimeoutData: (Duration, Cancellable) = (Duration.Undefined, ActorCell.emptyCancellable)
}

private[akka] trait ReceiveTimeout { this: ActorCell ?

  import ReceiveTimeout._
  import ActorCell._

  private var receiveTimeoutData: (Duration, Cancellable) = emptyReceiveTimeoutData

  final def receiveTimeout: Duration = receiveTimeoutData._1

  final def setReceiveTimeout(timeout: Duration): Unit = receiveTimeoutData = receiveTimeoutData.copy(_1 = timeout)

  final def checkReceiveTimeout() {
    val recvtimeout = receiveTimeoutData
    //Only reschedule if desired and there are currently no more messages to be processed
    if (!mailbox.hasMessages) recvtimeout._1 match {
      case f: FiniteDuration ?
        recvtimeout._2.cancel() //Cancel any ongoing future
        val task = system.scheduler.scheduleOnce(f, self, akka.actor.ReceiveTimeout)(this.dispatcher)
        receiveTimeoutData = (f, task)
      case _ ? cancelReceiveTimeout()
    }
    else cancelReceiveTimeout()

  }

  final def cancelReceiveTimeout(): Unit =
    if (receiveTimeoutData._2 ne emptyCancellable) {
      receiveTimeoutData._2.cancel()
      receiveTimeoutData = (receiveTimeoutData._1, emptyCancellable)
    }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:46,代码来源:ReceiveTimeout.scala


示例5: PinnedDispatcher

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

import akka.actor.ActorCell
import scala.concurrent.duration.Duration
import scala.concurrent.duration.FiniteDuration


class PinnedDispatcher(
  _configurator: MessageDispatcherConfigurator,
  _actor: ActorCell,
  _id: String,
  _shutdownTimeout: FiniteDuration,
  _threadPoolConfig: ThreadPoolConfig)
  extends Dispatcher(_configurator,
    _id,
    Int.MaxValue,
    Duration.Zero,
    _threadPoolConfig.copy(corePoolSize = 1, maxPoolSize = 1),
    _shutdownTimeout) {

  @volatile
  private var owner: ActorCell = _actor

  //Relies on an external lock provided by MessageDispatcher.attach
  protected[akka] override def register(actorCell: ActorCell) = {
    val actor = owner
    if ((actor ne null) && actorCell != actor) throw new IllegalArgumentException("Cannot register to anyone but " + actor)
    owner = actorCell
    super.register(actorCell)
  }
  //Relies on an external lock provided by MessageDispatcher.detach
  protected[akka] override def unregister(actor: ActorCell) = {
    super.unregister(actor)
    owner = null
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:37,代码来源:PinnedDispatcher.scala


示例6: CamelConfigSpec

//设置package包名称以及导入依赖的类
package akka.camel
import org.scalatest.Matchers
import org.scalatest.WordSpec
import akka.actor.ActorSystem
import scala.concurrent.duration.Duration
import java.util.concurrent.TimeUnit._
import akka.testkit.TestKit
import akka.util.Helpers.ConfigOps

class CamelConfigSpec extends WordSpec with Matchers {

  val (settings, config) = {
    val system = ActorSystem("CamelConfigSpec")
    val result = (CamelExtension(system).settings, system.settings.config)
    TestKit.shutdownActorSystem(system)
    result
  }
  "CamelConfigSpec" must {
    "have correct activationTimeout config" in {
      settings.ActivationTimeout should be(config.getMillisDuration("akka.camel.consumer.activation-timeout"))
    }

    "have correct autoAck config" in {
      settings.AutoAck should be(config.getBoolean("akka.camel.consumer.auto-ack"))
    }

    "have correct replyTimeout config" in {
      settings.ReplyTimeout should be(config.getMillisDuration("akka.camel.consumer.reply-timeout"))
    }

    "have correct streamingCache config" in {
      settings.StreamingCache should be(config.getBoolean("akka.camel.streamingCache"))
    }

    "have correct jmxStatistics config" in {
      settings.JmxStatistics should be(config.getBoolean("akka.camel.jmx"))
    }

    "have correct body conversions config" in {
      val conversions = config.getConfig("akka.camel.conversions")

      conversions.getString("file") should be("java.io.InputStream")
      conversions.entrySet.size should be(1)
    }

    "have correct Context Provider" in {
      settings.ContextProvider.isInstanceOf[DefaultContextProvider] should be(true)
    }
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:51,代码来源:CamelConfigSpec.scala


示例7: TransactorExtension

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

import akka.actor.{ ActorSystem, ExtensionId, ExtensionIdProvider, ExtendedActorSystem }
import akka.actor.Extension
import com.typesafe.config.Config
import akka.util.Timeout
import scala.concurrent.duration.Duration
import java.util.concurrent.TimeUnit.MILLISECONDS


@deprecated("akka.transactor will be removed", "2.3")
object TransactorExtension extends ExtensionId[TransactorSettings] with ExtensionIdProvider {
  override def get(system: ActorSystem): TransactorSettings = super.get(system)
  override def lookup: TransactorExtension.type = TransactorExtension
  override def createExtension(system: ExtendedActorSystem): TransactorSettings = new TransactorSettings(system.settings.config)
}

@deprecated("akka.transactor will be removed", "2.3")
class TransactorSettings(val config: Config) extends Extension {
  import config._
  val CoordinatedTimeout: Timeout = Timeout(Duration(getMilliseconds("akka.transactor.coordinated-timeout"), MILLISECONDS))
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:23,代码来源:TransactorExtension.scala


示例8: validJar

//设置package包名称以及导入依赖的类
package uk.co.telegraph.sbt.resolver

import java.util.zip.ZipFile

import sbt._
import scala.concurrent.duration.Duration
import scala.util._

trait ArtifactDeploy {

  private def validJar(file:File) = Try(new ZipFile(file)).isSuccess

  def apply(
    moduleId:ModuleID,
    targetDir:File,
    downloadIfOrderThan:Duration,
    logger: Logger
  )(implicit scalaVersion:String, repository:Repository):File = {

    def isStale(file:File) = moduleId.revision == LatestVersionLabel && System.currentTimeMillis - file.lastModified > downloadIfOrderThan.toMillis

    val localJar = new File(targetDir, s"${moduleId.name}.jar")

    if(!targetDir.exists()){
      logger.info(s"Creating target directory $targetDir")
      targetDir.mkdirs()
    }

    if(!localJar.exists() || isStale(localJar) || !validJar(localJar) ){
      Try{
        val remoteJar = moduleId.resolveVersion().remoteJar

        logger.info(s"Downloading jar from [$remoteJar] to [${localJar.getAbsolutePath}]")
        ( remoteJar #> localJar ).!!
      } match {
        case Success(_) =>
        case Failure(e) =>
          sys.error(s"Fail to download artifact [$moduleId]. Reason: ${e.getMessage}")
      }
    }
    if (!validJar(localJar)) {
      sys.error(s"Invalid jar file at [${localJar.getAbsolutePath}]")
    }
    localJar
  }
}

object ArtifactDeploy extends ArtifactDeploy 
开发者ID:telegraph,项目名称:sbt-wiremock,代码行数:49,代码来源:ArtifactDeploy.scala


示例9: ault

//设置package包名称以及导入依赖的类
package uk.co.telegraph.sbt.wiremock

import sbt._
import uk.co.telegraph.sbt.resolver._

import scala.concurrent.duration.Duration

trait WiremockKeys {

  lazy val wiremockVersion                  = SettingKey[Version ]("--version", "Wiremock version to download. Defaults to latest")
  lazy val wiremockDownloadDir              = SettingKey[File    ]("--download-dir", "The directory the Wiremock local jar will be downloaded to. Defaults to ./target.")
  lazy val wiremockDownloadIfOlderThan      = SettingKey[Duration]("--download-ttl", "Re-download the jar if the existing one is older than this. Defaults to 2 days.")

  lazy val wiremockHttpPort                 = SettingKey[Int           ]("--port", "Set the HTTP port number e.g. --port 9999")
  lazy val wiremockHttpsPort                = SettingKey[Option[Int]   ]("--https-port", "If specified, enables HTTPS on the supplied port.")
  lazy val wiremockBindAddress              = SettingKey[String        ]("--bind-address", "The IP address the WireMock server should serve from. Binds to all local network adapters if unspecified.")
  lazy val wiremockHttpsKeystore            = SettingKey[Option[File]  ]("--https-keystore", "Path to a keystore file containing an SSL certificate to use with HTTPS. The keystore must have a password of “password”. This option will only work if --https-port is specified. If this option isn’t used WireMock will default to its own self-signed certificate.")
  lazy val wiremockKeystorePassword         = SettingKey[Option[String]]("--keystore-password", "Password to the keystore, if something other than “password”.")
  lazy val wiremockHttpsTruststore          = SettingKey[Option[File]  ]("--https-truststore", "Path to a keystore file containing client certificates. See https and proxy-client-certs for details.")
  lazy val wiremockTruststorePassword       = SettingKey[Option[String]]("--truststore-password", "Optional password to the trust store. Defaults to “password” if not specified.")
  lazy val wiremockHttpsRequiredClientCert  = SettingKey[Boolean       ]("--https-require-client-cert", "Force clients to authenticate with a client certificate. See https for details.")
  lazy val wiremockVerbose                  = SettingKey[Boolean       ]("--verbose", "Turn on verbose logging to stdout")
  lazy val wiremockRootDir                  = SettingKey[File          ]("--root-dir", "Sets the root directory, under which mappings and __files reside. This defaults to the current directory.")
  lazy val wiremockRecordMapping            = SettingKey[Boolean       ]("--record-mappings", "Record incoming requests as stub mappings. See record-playback.")
  lazy val wiremockMatchHeaders             = SettingKey[Option[String]]("--match-headers", "When in record mode, capture request headers with the keys specified. See record-playback.")
  lazy val wiremockProxyAll                 = SettingKey[Option[URL]   ]("--proxy-all", "Proxy all requests through to another base URL e.g. --proxy-all=\"http://api.someservice.com\" Typically used in conjunction with --record-mappings such that a session on another service can be recorded.")
  lazy val wiremockPreserveHostHeader       = SettingKey[Boolean       ]("--preserve-host-header", "When in proxy mode, it passes the Host header as it comes from the client through to the proxied service. When this option is not present, the Host header value is deducted from the proxy URL. This option is only available if the --proxy-all option is specified.")
  lazy val wiremockProxyVia                 = SettingKey[Option[URL]   ]("--proxy-via", "When proxying requests (either by using –proxy-all or by creating stub mappings that proxy to other hosts), route via another proxy server (useful when inside a corporate network that only permits internet access via an opaque proxy). e.g. --proxy-via webproxy.mycorp.com (defaults to port 80) or --proxy-via webproxy.mycorp.com:8080")
  lazy val wiremockEnableBrowserProxying    = SettingKey[Boolean       ]("--enable-browser-proxying", "Run as a browser proxy. See browser-proxying.")
  lazy val wiremockNoRequestJournal         = SettingKey[Boolean       ]("--no-request-journal", "Disable the request journal, which records incoming requests for later verification. This allows WireMock to be run (and serve stubs) for long periods (without resetting) without exhausting the heap. The --record-mappings option isn’t available if this one is specified.")
  lazy val wiremockContainerThreads         = SettingKey[Option[Int]   ]("--container-threads", "The number of threads created for incoming requests. Defaults to 200.")
  lazy val wiremockMaxRequestJournalEntries = SettingKey[Option[Int]   ]("--max-request-journal-entries", "Set maximum number of entries in request journal (if enabled). When this limit is reached oldest entries will be discarded.")
  lazy val wiremockJettyAcceptorThreads     = SettingKey[Option[Int]   ]("--jetty-acceptor-threads", "The number of threads Jetty uses for accepting requests.")
  lazy val wiremockJettyAcceptQueueSize     = SettingKey[Option[Int]   ]("--jetty-accept-queue-size", "The Jetty queue size for accepted requests.")
  lazy val wiremockJettyHeaderBufferSize    = SettingKey[Option[Int]   ]("--jetty-header-buffer-size", "The Jetty buffer size for request headers, e.g. --jetty-header-buffer-size 16384, defaults to 8192K.")
//  lazy val wiremockExtensions               = SettingKey[String        ]("--extensions", "Extension class names e.g. com.mycorp.HeaderTransformer,com.mycorp.BodyTransformer. See extending-wiremock.")
  lazy val wiremockPrintAllNetworkTraffic   = SettingKey[Boolean       ]("--print-all-network-traffic", "Print all raw incoming and outgoing network traffic to console.")
  lazy val wiremockGlobalResponseTemplating = SettingKey[Boolean       ]("--global-response-templating", "Render all response definitions using Handlebars templates. --local-response-templating: Enable rendering of response definitions using Handlebars templates for specific stub mappings.")

  lazy val deployWiremock = TaskKey[File]("deploy-wiremock")
  lazy val startWiremock = TaskKey[String]("start-wiremock")
  lazy val stopWiremock = TaskKey[Unit]("stop-wiremock")
} 
开发者ID:telegraph,项目名称:sbt-wiremock,代码行数:44,代码来源:WiremockKeys.scala


示例10: CastleZookeeperConfig

//设置package包名称以及导入依赖的类
package com.box.castle.core.config

import java.util.concurrent.TimeUnit.SECONDS
import com.box.castle.core.config.CastleZookeeperConfig.{DefaultConnectionTimeout,
  DefaultInitialConnectTimeout, DefaultRetryPolicy, DefaultRoot, DefaultSessionTimeout}
import com.box.castle.common.Require
import org.apache.curator.RetryPolicy
import org.apache.curator.retry.ExponentialBackoffRetry

import scala.concurrent.duration.{Duration, FiniteDuration}


case class CastleZookeeperConfig(connect: String,
                                 root: String = DefaultRoot,
                                 sessionTimeout: Duration = DefaultSessionTimeout,
                                 connectionTimeout: Duration = DefaultConnectionTimeout,
                                 initialConnectTimeout: Duration = DefaultInitialConnectTimeout,
                                 retryPolicy: RetryPolicy = DefaultRetryPolicy) {
  Require.positiveDuration(sessionTimeout, "sessionTimeout")
  Require.positiveDuration(connectionTimeout, "connectionTimeout")
  Require.positiveDuration(initialConnectTimeout, "initialConnectTimeout")
}

object CastleZookeeperConfig {

  val DefaultRoot = "castle"
  val DefaultSessionTimeout = FiniteDuration(60, SECONDS)
  val DefaultConnectionTimeout = FiniteDuration(15, SECONDS)
  val DefaultInitialConnectTimeout = FiniteDuration(30, SECONDS)

  val DefaultExponentialBackoffBaseSleepTime = FiniteDuration(1, SECONDS)
  val DefaultExponentialBackoffMaxRetries: Int = 10
  val DefaultExponentialBackoffMaxSleepTime = FiniteDuration(60, SECONDS)

  val DefaultRetryPolicyType = "exponentialBackoff"

  val DefaultRetryPolicy = new ExponentialBackoffRetry(
    DefaultExponentialBackoffBaseSleepTime.toMillis.toInt,
    DefaultExponentialBackoffMaxRetries,
    DefaultExponentialBackoffMaxSleepTime.toMillis.toInt)
} 
开发者ID:Box-Castle,项目名称:core,代码行数:42,代码来源:CastleZookeeperConfig.scala


示例11: SidewalkSplit

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

import tosidewalk.model.driver.MyPostgresDriver.api._
import com.vividsolutions.jts.{ geom => jtsg }

import scala.concurrent.Await
import scala.concurrent.duration.Duration

case class SidewalkSplit(streetCurbId: Int, geom: jtsg.MultiLineString, sidewalkCount: Int)

class SidewalkSplitTable(tag: Tag) extends Table[SidewalkSplit](tag, Some("pittsburgh2"), "sidewalk_split") {
  def sidewalkSplitId = column[Int]("sidewalk_split_id", O.AutoInc, O.PrimaryKey)
  def geom = column[jtsg.MultiLineString]("geom")
  def sidewalkCount = column[Int]("sidewalk_count")

  def * = (sidewalkSplitId, geom, sidewalkCount) <> (SidewalkSplit.tupled, SidewalkSplit.unapply)
}

object SidewalkSplitTable {
  val db = Database.forConfig("default")
  val sidewalkSplits = TableQuery[SidewalkSplitTable]

  def select: List[SidewalkSplit] = {
    val q = sidewalkSplits.result
    Await.result(db.run(q), Duration.Inf).toList
  }
} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:28,代码来源:SidewalkSplitTable.scala


示例12: SidewalkEdgeStreetNode

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

import tosidewalk.model.driver.MyPostgresDriver.api._
import com.vividsolutions.jts.geom.Point

import scala.concurrent.Await
import scala.concurrent.duration.Duration


case class SidewalkEdgeStreetNode(sidewalkEdgeId: Int, streetNodeId: Int)

class SidewalkEdgeStreetNodeTable(tag: Tag) extends Table[SidewalkEdgeStreetNode](tag, Some("pittsburgh"), "sidewalk_edge_street_node") {
  def sidewalkEdgeId = column[Int]("sidewalk_edge_id")
  def streetNodeId = column[Int]("street_node_id")
  def * = (sidewalkEdgeId, streetNodeId) <> (SidewalkEdgeStreetNode.tupled, SidewalkEdgeStreetNode.unapply)
}

object SidewalkEdgeStreetNodeTable {
  val db = Database.forConfig("default")
  val sidewalkEdgeStreetNodeTable = TableQuery[SidewalkEdgeStreetNodeTable]

  def insert(sidewalkEdge: SidewalkEdge, streetNode: StreetNode) = {
    val q = DBIO.seq(
      sidewalkEdgeStreetNodeTable += SidewalkEdgeStreetNode(sidewalkEdge.sidewalkEdgeId, streetNode.streetNodeId)
    )
    Await.result(db.run(q), Duration.Inf)
  }

  def delete(hardDelete: Boolean = false): Unit = {
    val action = sidewalkEdgeStreetNodeTable.delete
    Await.result(db.run(action), Duration.Inf)
  }
} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:34,代码来源:SidewalkEdgeStreetNodeTable.scala


示例13: StreetCurb

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

import tosidewalk.model.driver.MyPostgresDriver.api._
import com.vividsolutions.jts.{ geom => jtsg }

import scala.concurrent.Await
import scala.concurrent.duration.Duration

case class StreetCurb(streetCurbId: Int, geom: jtsg.MultiLineString)

class StreetCurbTable(tag: Tag) extends Table[StreetCurb](tag, Some("pittsburgh"), "street_curb") {
  def streetCurbId = column[Int]("street_curb_id", O.AutoInc, O.PrimaryKey)
  def geom = column[jtsg.MultiLineString]("geom")
  def * = (streetCurbId, geom) <> (StreetCurb.tupled, StreetCurb.unapply)
}

object StreetCurbTable {
  val db = Database.forConfig("default")
  val streetCurbs = TableQuery[StreetCurbTable]

  def selectStreetCurbsIntersecting(buffer: jtsg.Geometry): List[StreetCurb] = {
    buffer.setSRID(4326)
    val q = streetCurbs.filter(_.geom.intersects(buffer.bind)).result
    Await.result(db.run(q), Duration.Inf).toList
  }
} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:27,代码来源:StreetCurbTable.scala


示例14: LimitedAction

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

import java.util.concurrent.TimeUnit

import scala.concurrent.duration.Duration


object LimitedAction {
  def apply(): LimitedAction = LimitedAction(Duration(60, TimeUnit.SECONDS), 1)
  def apply(limitedFor: Duration, maxTimes: Int) = new LimitedAction(limitedFor, maxTimes)
}

sealed class LimitedAction(limitedFor: Duration, maxTimes: Int) {

  private val limitedMillis = limitedFor.toMillis

  private var timestamp: Long = _
  private var currentTimes: Int = _

  private def isReady: Boolean = {
    if (timestamp != 0) {
      if (maxTimes > currentTimes) {
        currentTimes += 1
        timestamp = System.currentTimeMillis()
        true
      } else if (System.currentTimeMillis() - timestamp >= limitedMillis) {
        currentTimes = 0
        timestamp = System.currentTimeMillis()
        true
      } else {
        false
      }
    } else {
      timestamp = System.currentTimeMillis()
      true
    }
  }

  @inline final def foreach[A](ifReady: => A): Unit =
    if (isReady) ifReady

  @inline final def fold[A](ifNotReady: => A)(ifReady: => A): A =
    if (isReady) ifReady else ifNotReady
} 
开发者ID:fjaros,项目名称:init6,代码行数:45,代码来源:LimitedAction.scala


示例15: postStop

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

import java.util.concurrent.TimeUnit

import akka.actor.{ActorRef, Cancellable}
import com.init6.Init6Actor
import com.init6.users.KillConnection

import scala.concurrent.duration.Duration


trait Init6KeepAliveActor extends Init6Actor {

  private var pingTask: Cancellable = _
  protected var keptAlive = 0

  override def postStop(): Unit = {
    Option(pingTask).foreach(_.cancel())

    super.postStop()
  }

  def keepAlive(actor: ActorRef, f: () => Unit): Unit = {
    keepAlive(actor, f, 25, TimeUnit.SECONDS)
  }

  def keepAlive(actor: ActorRef, f: () => Unit, delay: Long, unit: TimeUnit): Unit = {
    val pingDuration = Duration(25, TimeUnit.SECONDS)
    import context.dispatcher

    pingTask = system.scheduler.schedule(
      pingDuration,
      pingDuration
    )({
        if (keptAlive < 4) {
          keptAlive += 1
          f()
        } else {
          actor ! KillConnection
        }
    })
  }
} 
开发者ID:fjaros,项目名称:init6,代码行数:44,代码来源:Init6KeepAliveActor.scala


示例16: Init6

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

import java.util.concurrent.TimeUnit

import akka.actor.{ActorRef, PoisonPill}
import com.init6.channels.ChannelsActor
import com.init6.connection.websocket.WebSocketConnectionHandler
import com.init6.connection.{ConnectionHandler, IpLimitActor}
import com.init6.db.{DAO, DAOActor}
import com.init6.servers.{ServerAnnouncementActor, ServerRegistry}
import com.init6.users.{RankingActor, TopCommandActor, UsersActor}

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.Random


object Init6 extends App with Init6Component {

  DAO
  ServerRegistry()
  DAOActor()
  IpLimitActor(Config().Accounts.connectionLimit)
  UsersActor()
  ChannelsActor()
  TopCommandActor()
  RankingActor()
  ServerAnnouncementActor(args(0).toLong)

  val random = new Random(System.nanoTime())
  val delay =
    if (random.nextInt(100) < Config().Server.reconThreshold) {
      0
    } else {
      12
    }

  var connectionHandlers: Seq[ActorRef] = _

  import system.dispatcher
  system.scheduler.scheduleOnce(
    Duration(delay, TimeUnit.SECONDS)
  )({
    connectionHandlers = Config().Server.ports
      .map(port => {
        ConnectionHandler(Config().Server.host, port)
      }) :+
      WebSocketConnectionHandler()
  })

  sys.addShutdownHook({
    Option(connectionHandlers).foreach(_.foreach(_ ! PoisonPill))

    implicit val timeout = Duration(10, TimeUnit.SECONDS)
    Await.ready(system.terminate(), timeout)
    DAO.close()
  })
} 
开发者ID:fjaros,项目名称:init6,代码行数:59,代码来源:Init6.scala


示例17: JSTimeoutThenIntervalTask

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

import scala.concurrent.duration.{Duration, FiniteDuration}

import akka.actor.Cancellable

class JSTimeoutThenIntervalTask(initialDelay: FiniteDuration,
    interval: FiniteDuration, task: => Any) extends Cancellable {

  private[this] var underlying: Cancellable = JSTimeoutTask(initialDelay) {
    underlying = JSIntervalTask(interval) {
      task
    }
    task
  }

  def isCancelled: Boolean = underlying.isCancelled

  def cancel(): Boolean = underlying.cancel()
}

object JSTimeoutThenIntervalTask {
  def apply(initialDelay: FiniteDuration, interval: FiniteDuration)(
      task: => Any): JSTimeoutThenIntervalTask =
    new JSTimeoutThenIntervalTask(initialDelay, interval, task)
} 
开发者ID:Starofall,项目名称:Chakka,代码行数:27,代码来源:JSTimeoutThenInterval.scala


示例18: AssignmentRepoSpec

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

import models.AssignmentRepo
import org.specs2.mutable.Specification
import play.api.Application
import play.api.test.WithApplication

import scala.concurrent.Await
import scala.concurrent.duration.Duration



class AssignmentRepoSpec extends Specification {

  sequential
  def assignmentRepo(implicit app: Application) = Application.instanceCache[AssignmentRepo].apply(app)

 "Awards repository" should {

   "get a record" in new WithApplication {
     val result = assignmentRepo.getAll
     val response = Await.result(result, Duration.Inf)
     response.head.name === "c++"
   }
   "delete a record" in new WithApplication {
     val result = assignmentRepo.delete(1)
     val response = Await.result(result, Duration.Inf)
     response === 1
   }
    "add a record" in new WithApplication {
         val result = assignmentRepo.add("scala", "2015-08-08", 22, "good",3)
         val response = Await.result(result, Duration.Inf)
         response === 1

 }
      "UPDATE a record" in new WithApplication {
       val result = assignmentRepo.update(1, "scala", "2015-08-08", 22, "good", 1)
       val response = Await.result(result, Duration.Inf)
     }
 "get record by id" in new WithApplication{
    val result = assignmentRepo.getById(1)
    val response = Await.result(result, Duration.Inf)
   response.get.name === "c++"
    }
    "get record by id" in new WithApplication{
    val result = assignmentRepo.getByUserId(1)
    val response = Await.result(result, Duration.Inf)

   response.head.name === "c++"
 }
  }
} 
开发者ID:aarwee,项目名称:PLAY-SLICK-DEEPTI-KUNAL-RISHABH,代码行数:53,代码来源:AssignmentRepoSpec.scala


示例19: LanguageRepoTest

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

import models.Language
import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner
import play.api.Application
import play.api.test.WithApplication

import scala.concurrent.Await
import scala.concurrent.duration.Duration

@RunWith(classOf[JUnitRunner])
class LanguageRepoTest extends Specification{

  def langRepo(implicit app:Application)=Application.instanceCache[LanguageRepo].apply(app)

  "Language Repository" should {
    "get language records" in new WithApplication {
      val res = langRepo.getAll()
      val response = Await.result(res, Duration.Inf)
      response.head.id ===1
    }

    "insert language records" in new WithApplication() {
      val res=langRepo.insert(1,"french","basic")
      val response=Await.result(res,Duration.Inf)
      response===1
    }


    "update language records" in new WithApplication(){
      val res=langRepo.update(1,"spansih","basic")
      val response=Await.result(res,Duration.Inf)
      response === 1
    }

    "delete language record" in new WithApplication() {
      val res=langRepo.delete("hindi")
      val response=Await.result(res,Duration.Inf)
      response===1
    }

    "get records by id" in new WithApplication() {
      val res=langRepo.getLanguage(1)
      val response=Await.result(res,Duration.Inf)
      response===Vector(Language(1,"hindi","advanced"))
    }


  }

} 
开发者ID:PallaviSingh1992,项目名称:Play-Slick-Assig2-v2,代码行数:54,代码来源:LanguageRepoTest.scala


示例20: Main

//设置package包名称以及导入依赖的类
import java.util.concurrent.TimeUnit

import akka.actor.{Props, ActorSystem}
import akka.util.Timeout
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.{Duration}

object Main extends App {
  println("Good morning everyone, time for another productive day...")
  val system = ActorSystem("jsonb")
  implicit val timeout = Timeout(10, TimeUnit.SECONDS)

  val rand = new scala.util.Random
  val turns = 100
  val gameSpeedMultiplier = 1.0
  val hireSpeed = Duration((4000 / gameSpeedMultiplier).toInt, TimeUnit.MILLISECONDS)
  val turnSpeed = Duration((1500 / gameSpeedMultiplier).toInt, TimeUnit.MILLISECONDS)

  val Christian = system.actorOf(Props(new OverlordActor(gameSpeedMultiplier)), "Christian")
  val HR = system.actorOf(Props(new HRActor(Christian)), "Toni")
  val Instigator = system.actorOf(Props(new InstigatorActor(Christian)), "jsonB")

  val zero = Duration(0, TimeUnit.MILLISECONDS)
  HR.tell(RecruitSomeone, null)
  HR.tell(RecruitSomeone, null)
  HR.tell(RecruitSomeone, null)
  system.scheduler.schedule(zero, hireSpeed, HR, RecruitSomeone)
  system.scheduler.schedule(zero, turnSpeed, Instigator, Instigate)
} 
开发者ID:TimeBomb,项目名称:Office-Warefare-Simulator,代码行数:30,代码来源:Main.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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