Example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadScheduledExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor.

Prototype

public static ScheduledExecutorService newSingleThreadScheduledExecutor() 

Source Link

Document

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:com.adaptris.core.jms.FailoverJmsProducerCase.java

public void testEventuallyConnects() throws Exception {
    final EmbeddedActiveMq broker = new EmbeddedActiveMq();
    FailoverJmsConnection connection = new FailoverJmsConnection();
    connection.addConnection(new JmsConnection(new BasicActiveMqImplementation("tcp://localhost:123456")));
    connection.addConnection(broker.getJmsConnection(new BasicActiveMqImplementation(), true));
    connection.setConnectionRetryInterval(new TimeInterval(250L, TimeUnit.MILLISECONDS));
    connection.addExceptionListener(new StandaloneConsumer());
    connection.setRegisterOwner(true);/*  w w  w .  j a  v a 2  s  .  co  m*/
    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    try {
        es.schedule(new Runnable() {

            @Override
            public void run() {
                try {
                    broker.start();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

        }, 2L, TimeUnit.SECONDS);
        LifecycleHelper.initAndStart(connection);
    } finally {
        broker.destroy();
        LifecycleHelper.stopAndClose(connection);
        es.shutdownNow();
    }
}

From source file:org.springframework.batch.admin.jmx.StepExecutionServiceLevelMonitor.java

public void invoke(ProceedingJoinPoint joinPoint, final StepExecution stepExecution, Step step)
        throws Throwable {

    final AtomicBoolean finished = new AtomicBoolean(false);
    final StopWatch timer = new StopWatch(stepExecution.getStepName() + ":execution");

    try {/*from  ww w  .j ava2s.  co m*/

        if (timeout > 0) {

            if (notificationPublisher != null) {
                Notification notification = new Notification("INFO", this, sequence++,
                        "Starting:" + stepExecution);
                notificationPublisher.sendNotification(notification);
            }

            timer.start("StepExecution.Id:" + stepExecution.getId());
            final long threshold = (long) (timeout * (1 - warningMargin));
            Date warningTime = new Date(System.currentTimeMillis() + threshold);
            logger.debug("Scheduling warning after (ms) " + threshold);
            taskScheduler.schedule(new Runnable() {

                public void run() {
                    if (!finished.get()) {
                        logger.debug("Sending warning (step not complete after " + threshold + " ms): "
                                + stepExecution);
                        if (notificationPublisher != null) {
                            Notification notification = new Notification("WARN",
                                    StepExecutionServiceLevelMonitor.this, sequence++,
                                    "Warning:" + stepExecution);
                            notificationPublisher.sendNotification(notification);
                        }
                    } else {
                        logger.debug("No warning necessary for " + stepExecution);
                    }
                }

            }, warningTime);
        }

        joinPoint.proceed();

    } finally {

        finished.set(true);

        if (timeout > 0) {
            timer.stop();
            Executors.newSingleThreadScheduledExecutor().shutdown();
            if (timer.getLastTaskTimeMillis() > timeout) {
                overruns++;
                logger.debug("Notifying overrun " + stepExecution);
                if (notificationPublisher != null) {
                    Notification notification = new Notification("ERROR", this, sequence++,
                            "Overrun:" + stepExecution);
                    notificationPublisher.sendNotification(notification);
                }
            }
        }

    }

}

From source file:org.wso2.andes.server.cluster.RDBMSCoordinationStrategy.java

/**
 * Default constructor/*w  ww  . ja  v a2 s.c om*/
 */
RDBMSCoordinationStrategy() {
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("RDBMSCoordinationStrategy-%d")
            .build();
    threadExecutor = Executors.newSingleThreadExecutor(namedThreadFactory);
    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    heartBeatInterval = AndesConfigurationManager
            .readValue(AndesConfiguration.RDBMS_BASED_COORDINATION_HEARTBEAT_INTERVAL);
    coordinatorEntryCreationWaitTime = AndesConfigurationManager
            .readValue(AndesConfiguration.RDBMS_BASED_COORDINATOR_ENTRY_CREATION_WAIT_TIME);
    //(heartBeatInterval / 2) + 1;

    // Maximum age of a heartbeat. After this much of time, the heartbeat is considered invalid and node is
    // considered to have left the cluster.
    heartbeatMaxAge = heartBeatInterval * 2;

    if (heartBeatInterval <= coordinatorEntryCreationWaitTime) {
        throw new RuntimeException(
                "Configuration error. " + AndesConfiguration.RDBMS_BASED_COORDINATION_HEARTBEAT_INTERVAL
                        + " * 2 should be greater than "
                        + AndesConfiguration.RDBMS_BASED_COORDINATOR_ENTRY_CREATION_WAIT_TIME);
    }
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.SimpleMessageConsumer.java

public SimpleMessageConsumer(final MetaMessageSessionFactory messageSessionFactory,
        final RemotingClientWrapper remotingClient, final ConsumerConfig consumerConfig,
        final ConsumerZooKeeper consumerZooKeeper, final ProducerZooKeeper producerZooKeeper,
        final SubscribeInfoManager subscribeInfoManager, final RecoverManager recoverManager,
        final OffsetStorage offsetStorage, final LoadBalanceStrategy loadBalanceStrategy) {
    super();//  w w w  .j  a v  a2 s.  co  m
    this.messageSessionFactory = messageSessionFactory;
    this.remotingClient = remotingClient;
    this.consumerConfig = consumerConfig;
    this.producerZooKeeper = producerZooKeeper;
    this.consumerZooKeeper = consumerZooKeeper;
    this.offsetStorage = offsetStorage;
    this.subscribeInfoManager = subscribeInfoManager;
    this.recoverStorageManager = recoverManager;
    this.fetchManager = new SimpleFetchManager(consumerConfig, this);
    this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    this.loadBalanceStrategy = loadBalanceStrategy;
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            SimpleMessageConsumer.this.consumerZooKeeper.commitOffsets(SimpleMessageConsumer.this.fetchManager);
        }
    }, consumerConfig.getCommitOffsetPeriodInMills(), consumerConfig.getCommitOffsetPeriodInMills(),
            TimeUnit.MILLISECONDS);
    createFilter(consumerConfig);
}

From source file:org.onebusaway.gtfs_realtime.producer_demo.GtfsRealtimeProviderImpl.java

/**
 * The start method automatically starts up a recurring task that periodically
 * downloads the latest alerts from the SEPTA alerts stream and processes
 * them.//from  w  w w  .ja v a  2  s.  c  om
 */
@PostConstruct
public void start() {
    _executor = Executors.newSingleThreadScheduledExecutor();
    _log.info("starting GTFS-realtime service");
    _executor.scheduleAtFixedRate(new BusListRefreshTask(), 0, _busListInterval, TimeUnit.SECONDS);
    _executor.scheduleAtFixedRate(new LocationRefreshTask(), 0, _refreshInterval, TimeUnit.SECONDS);
}

From source file:org.onebusaway.gtfs_realtime.trip_updates.GtfsRealtimeProviderImpl.java

/**
 * The start method automatically starts up a recurring task that periodically
 * downloads the latest alerts from the SEPTA alerts stream and processes
 * them./*from   w  w w .j  av a2s  .co  m*/
 */
@PostConstruct
public void start() {
    _executor = Executors.newSingleThreadScheduledExecutor();
    _log.info("starting GTFS-realtime service");
    _executor.scheduleAtFixedRate(new BusListRefreshTask(), 0, _busListInterval, TimeUnit.SECONDS);
    _executor.scheduleAtFixedRate(new UpdateRefreshTask(), 0, _refreshInterval, TimeUnit.SECONDS);
}

From source file:org.wso2.carbon.cloud.gateway.transport.CGTransportSender.java

@Override
public void init(ConfigurationContext cfgCtx, TransportOutDescription transportOut) throws AxisFault {
    super.init(cfgCtx, transportOut);
    builder = new BinaryRelayBuilder();
    formatter = new ExpandingMessageFormatter();

    semaphoreTimeOut = CGUtils.getLongProperty(CGConstant.CG_SEMAPHORE_TIMEOUT, 86400L);

    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    String groupName = "CGTransportSender-tenant-" + tenantId + "-worker-thread-group";
    String groupId = "CGTransportSender-tenant-" + tenantId + "-worker";

    workerPool = WorkerPoolFactory.getWorkerPool(
            CGUtils.getIntProperty(CGConstant.CG_T_CORE, CGConstant.WORKERS_CORE_THREADS),
            CGUtils.getIntProperty(CGConstant.CG_T_MAX, CGConstant.WORKERS_MAX_THREADS),
            CGUtils.getIntProperty(CGConstant.CG_T_ALIVE, CGConstant.WORKER_KEEP_ALIVE),
            CGUtils.getIntProperty(CGConstant.CG_T_QLEN, CGConstant.WORKER_BLOCKING_QUEUE_LENGTH), groupName,
            groupId);//  ww  w . ja v a  2s.co m

    //let the task run per once a day by default
    String timeUnitAsString = CGUtils.getStringProperty(CGConstant.TIME_UNIT, CGConstant.HOUR);

    // both the scheduler and the idle message time will be used the same time unit
    // given by CGConstant#TIME_UNIT
    long noOfSchedulerTimeUnits = CGUtils.getLongProperty(CGConstant.NO_OF_SCHEDULER_TIME_UNITS, 24L);
    long noOfIdleMessageUnits = CGUtils.getLongProperty(CGConstant.NO_OF_IDLE_MESSAGE_TIME_UNITS, 24L);

    checkSchedulePreConditions(timeUnitAsString, noOfIdleMessageUnits, noOfSchedulerTimeUnits);
    TimeUnit schedulerTimeUnit = getTimeUnit(timeUnitAsString);

    // schedule the message clean up task in order to avoid server goes OOM in case of the
    // back end server is offline
    deadMsgCleanupScheduler = Executors.newSingleThreadScheduledExecutor();
    deadMsgCleanupScheduler.scheduleWithFixedDelay(
            new DeadMessageCleanupTask(CGThriftServerHandler.getRequestBuffers(),
                    getDurationAsMillisecond(schedulerTimeUnit, noOfIdleMessageUnits)),
            noOfSchedulerTimeUnits, noOfSchedulerTimeUnits, schedulerTimeUnit);

    // start the response message dispatching tasks
    int noOfDispatchingTask = CGUtils.getIntProperty(CGConstant.NO_OF_DISPATCH_TASK, 2);
    for (int i = 0; i < noOfDispatchingTask; i++) {
        workerPool.execute(new ResponseMessageDispatchingTask());
    }

    log.info("CGTransportSender started for tenant [" + tenantId + "]...");
}

From source file:org.apache.hadoop.mapred.JobTrackerHAServiceProtocol.java

@Override
public void transitionToActive(StateChangeRequestInfo reqInfo)
        throws ServiceFailedException, AccessControlException, IOException {
    if (haState == HAServiceState.ACTIVE) {
        LOG.info("Already in active state.");
        return;/*from www . java  2s  .c o m*/
    }
    LOG.info("Transitioning to active");
    try {
        httpRedirector.stop();
        JobConf jtConf = new JobConf(conf);
        currentSysDir = rollSystemDirectory(jtConf);
        // Update the conf for the JT so the address is resolved
        HAUtil.setJtRpcAddress(jtConf);

        jtRunner.startJobTracker(jtConf);
    } catch (Throwable t) {
        doImmediateShutdown(t);
    }
    long activeCheckMillis = conf.getLong(HAUtil.MR_HA_ACTIVE_CHECK_MILLIS,
            HAUtil.MR_HA_ACTIVE_CHECK_MILLIS_DEFAULT);
    sysDirMonitorExecutor = Executors.newSingleThreadScheduledExecutor();
    sysDirMonitorExecutor.scheduleWithFixedDelay(new SystemDirectoryMonitor(), activeCheckMillis,
            activeCheckMillis, TimeUnit.MILLISECONDS);
    haState = HAServiceState.ACTIVE;
    LOG.info("Transitioned to active");
}

From source file:org.apache.hedwig.server.netty.TestPubSubServer.java

@Test(timeout = 60000)
public void testUncaughtExceptionInNettyThread() throws Exception {

    SynchronousQueue<Throwable> queue = new SynchronousQueue<Throwable>();
    RecordingUncaughtExceptionHandler uncaughtExceptionHandler = new RecordingUncaughtExceptionHandler(queue);
    final int port = PortManager.nextFreePort();

    PubSubServer server = startServer(uncaughtExceptionHandler, port, new TopicManagerInstantiator() {

        @Override//from   w w  w.  j  a v  a2s .com
        public TopicManager instantiateTopicManager() throws IOException {
            return new AbstractTopicManager(new ServerConfiguration(),
                    Executors.newSingleThreadScheduledExecutor()) {
                @Override
                protected void realGetOwner(ByteString topic, boolean shouldClaim,
                        Callback<HedwigSocketAddress> cb, Object ctx) {
                    throw new RuntimeException("this exception should be uncaught");
                }

                @Override
                protected void postReleaseCleanup(ByteString topic, Callback<Void> cb, Object ctx) {
                }
            };
        }
    });

    runPublishRequest(port);
    assertEquals(RuntimeException.class, queue.take().getClass());
    server.shutdown();
}

From source file:org.jorge.lolin1.ui.activities.DrawerLayoutFragmentActivity.java

@Override
public void onNavigationDrawerItemSelected(int position) {
    if (!navigatedItemsStack.isEmpty() && position == getLastSelectedNavDrawerIndex()) {
        //We don't want to perform an unnecessary Activity reload
        //noinspection UnnecessaryReturnStatement
        return;/*from w ww.jav  a 2 s .c om*/
    } else {
        navigatedItemsStack.push(position);
    }

    Runnable task;
    switch (position) {
    case 0:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), NewsReaderActivity.class));
            }
        };
        break;
    case 1:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), JungleTimersActivity.class));
            }
        };
        break;
    case 2:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), ChampionListActivity.class));
            }
        };
        break;
    case 3:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), SurrReaderActivity.class));
            }
        };
        break;
    case 4:
        task = new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(getApplicationContext(), ChatOverviewActivity.class));
            }
        };
        break;
    default:
        Crashlytics.log(Log.ERROR, "debug", "Should never happen - Selected index - " + position);
        task = null;
    }
    if (task != null) {
        ScheduledExecutorService newActivityExecutor = Executors.newSingleThreadScheduledExecutor();
        newActivityExecutor.schedule(task, 0, TimeUnit.MILLISECONDS);
    }
}