當前位置: 首頁>>代碼示例>>Java>>正文


Java FiniteDuration.create方法代碼示例

本文整理匯總了Java中scala.concurrent.duration.FiniteDuration.create方法的典型用法代碼示例。如果您正苦於以下問題:Java FiniteDuration.create方法的具體用法?Java FiniteDuration.create怎麽用?Java FiniteDuration.create使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在scala.concurrent.duration.FiniteDuration的用法示例。


在下文中一共展示了FiniteDuration.create方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: scheduleWeeklyReport

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
private void scheduleWeeklyReport() {
    FiniteDuration delay = FiniteDuration.create(secondsUntilNextMondayRun(), TimeUnit.SECONDS);
    Cancellable reportTask = tasks.remove("REPORT_SENDER");
    if (reportTask != null) {
        reportTask.cancel();
    }
    tasks.put("REPORT_SENDER", system.scheduler().scheduleOnce(delay, () -> {
        Logger.info("Running weekly email report");
        List<User> teachers = Ebean.find(User.class)
                .fetch("language")
                .where()
                .eq("roles.name", "TEACHER")
                .findList();
        teachers.forEach(t -> {
            try {
                composer.composeWeeklySummary(t);
            } catch (RuntimeException e) {
                Logger.error("Failed to send email for {}", t.getEmail());
            }
        });
        // Reschedule
        scheduleWeeklyReport();
    }, system.dispatcher()));
}
 
開發者ID:CSCfi,項目名稱:exam,代碼行數:25,代碼來源:SystemInitializer.java

示例2: transferComplete

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
/**
 * This method is invoked when leadership transfer was carried out and complete.
 */
public void transferComplete() {
    LOG.debug("{}: leader transfer complete - waiting for new leader", raftActor.persistenceId());

    // We'll give it a little time for the new leader to be elected to give the derived class a
    // chance to possibly complete work that was suspended while we were transferring. The
    // RequestVote message from the new leader candidate should cause us to step down as leader
    // and convert to follower due to higher term. We should then get an AppendEntries heart
    // beat with the new leader id.

    // Add a timer in case we don't get a leader change. Note: the Runnable is sent as a message to the raftActor
    // which executes it safely run on the actor's thread dispatcher.
    FiniteDuration timeout = FiniteDuration.create(newLeaderTimeoutInMillis, TimeUnit.MILLISECONDS);
    newLeaderTimer = raftActor.getContext().system().scheduler().scheduleOnce(timeout, raftActor.self(),
        (Runnable) () -> {
            LOG.debug("{}: leader not elected in time", raftActor.persistenceId());
            finish(true);
        }, raftActor.getContext().system().dispatcher(), raftActor.self());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:22,代碼來源:RaftActorLeadershipTransferCohort.java

示例3: sendShutDown

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
private void sendShutDown(final ActorRef actor) throws Exception {
    testLog.info("sendShutDown for {} starting", actor.path());

    FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
    Future<Boolean> stopFuture = Patterns.gracefulStop(actor, duration, Shutdown.INSTANCE);

    Boolean stopped = Await.result(stopFuture, duration);
    assertEquals("Stopped", Boolean.TRUE, stopped);

    testLog.info("sendShutDown for {} ending", actor.path());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:12,代碼來源:LeadershipTransferIntegrationTest.java

示例4: testCommonConfigOverride

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
@Test
public void testCommonConfigOverride() {

    int expectedCapacity = 123;
    String timeoutValue = "1000ms";
    CommonConfig config = new CommonConfig.Builder<>("testsystem")
            .mailboxCapacity(expectedCapacity)
            .mailboxPushTimeout(timeoutValue)
            .metricCaptureEnabled(true)
            .build();

    assertEquals(expectedCapacity, config.getMailBoxCapacity().intValue());

    FiniteDuration expectedTimeout = FiniteDuration.create(1000, TimeUnit.MILLISECONDS);
    assertEquals(expectedTimeout.toMillis(), config.getMailBoxPushTimeout().toMillis());

    assertTrue(config.isMetricCaptureEnabled());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:19,代碼來源:CommonConfigTest.java

示例5: testConfigCustomizations

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
@Test
public void testConfigCustomizations() {

    AkkaConfigurationReader reader = new TestConfigReader();

    final int expectedCapacity = 100;
    String timeOutVal = "10ms";
    FiniteDuration expectedTimeout = FiniteDuration.create(10, TimeUnit.MILLISECONDS);

    RemoteRpcProviderConfig config = new RemoteRpcProviderConfig.Builder("unit-test")
            .metricCaptureEnabled(true)//enable metric capture
            .mailboxCapacity(expectedCapacity)
            .mailboxPushTimeout(timeOutVal)
            .withConfigReader(reader)
            .build();

    Assert.assertTrue(config.isMetricCaptureEnabled());
    Assert.assertEquals(expectedCapacity, config.getMailBoxCapacity().intValue());
    Assert.assertEquals(expectedTimeout.toMillis(), config.getMailBoxPushTimeout().toMillis());

    //Now check this config inside an actor
    ActorSystem system = ActorSystem.create("unit-test", config.get());
    TestActorRef<ConfigTestActor> configTestActorTestActorRef =
            TestActorRef.create(system, Props.create(ConfigTestActor.class));

    ConfigTestActor actor = configTestActorTestActorRef.underlyingActor();
    Config actorConfig = actor.getConfig();

    config = new RemoteRpcProviderConfig(actorConfig);

    Assert.assertTrue(config.isMetricCaptureEnabled());
    Assert.assertEquals(expectedCapacity, config.getMailBoxCapacity().intValue());
    Assert.assertEquals(expectedTimeout.toMillis(), config.getMailBoxPushTimeout().toMillis());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:35,代碼來源:RemoteRpcProviderConfigTest.java

示例6: sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
private void sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1() throws Exception {
    testLog.info("sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1 starting");

    clearMessages(leaderNotifierActor);
    clearMessages(follower1NotifierActor);
    clearMessages(follower2NotifierActor);
    clearMessages(follower3NotifierActor);

    // Simulate a delay for follower2 in receiving the LeaderTransitioning message with null leader id.
    final TestRaftActor follower2Instance = follower2Actor.underlyingActor();
    follower2Instance.startDropMessages(LeaderTransitioning.class);

    FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
    final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);

    verifyRaftState(follower1Actor, RaftState.Leader);

    Boolean stopped = Await.result(stopFuture, duration);
    assertEquals("Stopped", Boolean.TRUE, stopped);

    // Re-enable LeaderTransitioning messages to follower2.
    final LeaderTransitioning leaderTransitioning = expectFirstMatching(follower2CollectorActor,
            LeaderTransitioning.class);
    follower2Instance.stopDropMessages(LeaderTransitioning.class);

    follower2Instance.stopDropMessages(AppendEntries.class);
    ApplyState applyState = expectFirstMatching(follower2CollectorActor, ApplyState.class);
    assertEquals("Apply sate index", 0, applyState.getReplicatedLogEntry().getIndex());

    // Now send the LeaderTransitioning to follower2 after it has received AppendEntries from the new leader.
    follower2Actor.tell(leaderTransitioning, ActorRef.noSender());

    verifyLeaderStateChangedMessages(leaderNotifierActor, null, follower1Id);
    verifyLeaderStateChangedMessages(follower1NotifierActor, null, follower1Id);
    // follower2 should only get 1 LeaderStateChanged with the new leaderId - the LeaderTransitioning message
    // should not generate a LeaderStateChanged with null leaderId since it arrived after the new leaderId was set.
    verifyLeaderStateChangedMessages(follower2NotifierActor, follower1Id);
    verifyLeaderStateChangedMessages(follower3NotifierActor, null, follower1Id);

    testLog.info("sendShutDownToLeaderAndVerifyLeadershipTransferToFollower1 ending");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:42,代碼來源:LeadershipTransferIntegrationTest.java

示例7: sendResponse

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
        final boolean wantShardReady, final Supplier<Object> messageSupplier) {
    if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
        if (doWait) {
            final ActorRef sender = getSender();
            final ActorRef self = self();

            Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);

            OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
                new OnShardInitialized(replyRunnable);

            shardInformation.addOnShardInitialized(onShardInitialized);

            FiniteDuration timeout = shardInformation.getDatastoreContext()
                    .getShardInitializationTimeout().duration();
            if (shardInformation.isShardInitialized()) {
                // If the shard is already initialized then we'll wait enough time for the shard to
                // elect a leader, ie 2 times the election timeout.
                timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
                        .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
            }

            LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
                    shardInformation.getShardName());

            Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
                    timeout, getSelf(),
                    new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
                    getContext().dispatcher(), getSelf());

            onShardInitialized.setTimeoutSchedule(timeoutSchedule);

        } else if (!shardInformation.isShardInitialized()) {
            LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
                    shardInformation.getShardName());
            getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
        } else {
            LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
                    shardInformation.getShardName());
            getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
        }

        return;
    }

    getSender().tell(messageSupplier.get(), getSelf());
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:49,代碼來源:ShardManager.java

示例8: testLeadershipTransferOnShutdown

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
@Test
public void testLeadershipTransferOnShutdown() throws Exception {
    //TODO remove when test passes also for ClientBackedDataStore
    Assume.assumeTrue(testParameter.equals(DistributedDataStore.class));
    leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
    followerDatastoreContextBuilder.shardElectionTimeoutFactor(10).customRaftPolicyImplementation(null);
    final String testName = "testLeadershipTransferOnShutdown";
    initDatastores(testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, CARS_AND_PEOPLE);

    final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
            DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(100),
            commitTimeout);
    try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
            testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {

        followerTestKit.waitForMembersUp("member-3");
        follower2TestKit.waitForMembersUp("member-1", "member-2");

        // Create and submit a couple tx's so they're pending.

        DOMStoreWriteTransaction writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
        writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
        writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
        writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
        final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();

        IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
            stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));

        writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
        final MapEntryNode car = CarsModel.newCarEntry("optima", BigInteger.valueOf(20000));
        writeTx.write(CarsModel.newCarPath("optima"), car);
        final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();

        IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
            stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));

        // Gracefully stop the leader via a Shutdown message.

        sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
            .shardElectionTimeoutFactor(100));

        final FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
        final Future<ActorRef> future = leaderDistributedDataStore.getActorContext().findLocalShardAsync("cars");
        final ActorRef leaderActor = Await.result(future, duration);

        final Future<Boolean> stopFuture = Patterns.gracefulStop(leaderActor, duration, Shutdown.INSTANCE);

        // Commit the 2 transactions. They should finish and succeed.

        followerTestKit.doCommit(cohort1);
        followerTestKit.doCommit(cohort2);

        // Wait for the leader actor stopped.

        final Boolean stopped = Await.result(stopFuture, duration);
        assertEquals("Stopped", Boolean.TRUE, stopped);

        // Verify leadership was transferred by reading the committed data from the other nodes.

        verifyCars(followerDistributedDataStore.newReadOnlyTransaction(), car);
        verifyCars(follower2DistributedDataStore.newReadOnlyTransaction(), car);
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:65,代碼來源:DistributedDataStoreRemotingIntegrationTest.java

示例9: testShutDown

import scala.concurrent.duration.FiniteDuration; //導入方法依賴的package包/類
@Test
public void testShutDown() throws Exception {
    LOG.info("testShutDown starting");
    new JavaTestKit(getSystem()) {
        {
            MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
                    .put("shard1", Arrays.asList("member-1")).put("shard2", Arrays.asList("member-1")).build());

            String shardId1 = ShardIdentifier.create("shard1", MEMBER_1, shardMrgIDSuffix).toString();
            ActorRef shard1 = actorFactory.createActor(MessageCollectorActor.props(), shardId1);

            String shardId2 = ShardIdentifier.create("shard2", MEMBER_1, shardMrgIDSuffix).toString();
            ActorRef shard2 = actorFactory.createActor(MessageCollectorActor.props(), shardId2);

            ActorRef shardManager = actorFactory.createActor(newTestShardMgrBuilder(mockConfig)
                    .addShardActor("shard1", shard1).addShardActor("shard2", shard2).props());

            shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
            shardManager.tell(new ActorInitialized(), shard1);
            shardManager.tell(new ActorInitialized(), shard2);

            FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
            Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);

            MessageCollectorActor.expectFirstMatching(shard1, Shutdown.class);
            MessageCollectorActor.expectFirstMatching(shard2, Shutdown.class);

            try {
                Await.ready(stopFuture, FiniteDuration.create(500, TimeUnit.MILLISECONDS));
                fail("ShardManager actor stopped without waiting for the Shards to be stopped");
            } catch (TimeoutException e) {
                // expected
            }

            actorFactory.killActor(shard1, this);
            actorFactory.killActor(shard2, this);

            Boolean stopped = Await.result(stopFuture, duration);
            assertEquals("Stopped", Boolean.TRUE, stopped);
        }
    };

    LOG.info("testShutDown ending");
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:45,代碼來源:ShardManagerTest.java


注:本文中的scala.concurrent.duration.FiniteDuration.create方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。