当前位置: 首页>>代码示例>>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;未经允许,请勿转载。