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:org.ulyssis.ipp.reader.Reader.java

/**
 * Create a new reader and connect to Redis.
 * //from  ww  w.  jav  a2 s .  c om
 * options are passed in, rather than
 * accessed through a singleton or such, to improve testability
 * and modularity, and to prevent hidden dependencies and
 * eventual threading issues.
 * 
 * @param options
 *           The command line options to use for this reader.
 */
public Reader(ReaderOptions options) {
    this.options = options;
    this.readerConfig = Config.getCurrentConfig().getReader(options.getId());
    this.llrpReader = new LLRPReader(this::messageReceived, this::errorOccurred);

    if (readerConfig.getType() == ReaderConfig.Type.SIMULATOR) {
        executorService = Executors.newSingleThreadScheduledExecutor();
    } else {
        executorService = null;
    }

    if (options.getNoRedis()) {
        LOG.info("Not using Redis, setting initial update count to 0.");
        this.updateCount = 0L;
        this.jedis = null;
    } else {
        this.jedis = JedisHelper.get(readerConfig.getURI());
        try {
            this.updateCount = jedis.llen("updates");
        } catch (JedisConnectionException e) {
            LOG.error("Couldn't connect to Jedis when getting update count. Setting 0 instead.", e);
            this.updateCount = 0L; // TODO: Is 0 appropriate?
        }
    }
    String statusChannel = Config.getCurrentConfig().getStatusChannel();
    this.statusReporter = new StatusReporter(readerConfig.getURI(), statusChannel);
    String controlChannel = Config.getCurrentConfig().getControlChannel();
    this.commandProcessor = new CommandProcessor(readerConfig.getURI(), controlChannel, statusReporter);
    commandProcessor.addHandler(new PingHandler());
    this.updateChannel = JedisHelper.dbLocalChannel(Config.getCurrentConfig().getUpdateChannel(),
            readerConfig.getURI());

    options.getReplayFile().ifPresent(replayFile -> {
        try {
            LOG.info("Opening replay file: {}", replayFile);
            ByteChannel channel = Files.newByteChannel(replayFile, StandardOpenOption.APPEND,
                    StandardOpenOption.CREATE);
            this.replayChannel = Optional.of(channel);
        } catch (IOException e) {
            LOG.error("Couldn't open channel for logging to replay file: {}", replayFile, e);
        }
    });

    this.lastUpdateForTag = new HashMap<>();
}

From source file:com.graphaware.importer.context.BaseImportContext.java

/**
 * {@inheritDoc}/*  ww  w. j a va2  s . c o  m*/
 */
@Override
public final void shutdown() {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            LOG.info("I am still alive!");
        }
    }, 1, 1, TimeUnit.MINUTES);

    preShutdown();

    indexProvider().shutdown();

    inserter().shutdown();

    postShutdown();

    executor.shutdownNow();
}

From source file:au.com.jwatmuff.eventmanager.Main.java

private static void monitorNetworkInterfaceChanges(final PeerManager peerManager) {
    Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
        @Override/* w  w  w .j av a2  s  .  c o m*/
        public void run() {
            if (updateRmiHostName()) {
                peerManager.refreshServices();
            }
        }
    }, 15, 15, TimeUnit.SECONDS);
}

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

/**
 * The start method automatically starts up a recurring task that periodically
 * downloads the latest vehicle data from the SEPTA vehicle stream and
 * processes them.//from   w  w  w  . java2s  .c  o  m
 */
@PostConstruct
public void start() {
    _log.info("starting GTFS-realtime service");
    _executor = Executors.newSingleThreadScheduledExecutor();
    _executor.scheduleAtFixedRate(new VehiclesRefreshTask(), 0, _refreshInterval, TimeUnit.SECONDS);
}

From source file:net.simondieterle.wns.server.Sender.java

@VisibleForTesting
public Sender(String id, String secret, int retryCount) {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    this.clientId = id;
    this.clientSecret = secret;

    this.client = HttpAsyncClients.custom().setMaxConnTotal(100).setMaxConnPerRoute(10).build();

    this.authExecutor = new AsyncRetryExecutor(scheduler).retryOn(ServerFailedException.class)
            .withExponentialBackoff(10, 2.0).withMaxRetries(5).withUniformJitter().withMaxDelay(60000);

    this.executor = new AsyncRetryExecutor(scheduler).retryOn(ServerFailedException.class)
            .retryOn(TimeoutException.class).retryOn(IOException.class).withExponentialBackoff(100, 2.0)
            .withUniformJitter().withMaxDelay(4000).withMaxRetries(retryCount);

    this.client.start();

}

From source file:com.taobao.metamorphosis.client.http.SimpleHttpConsumer.java

public SimpleHttpConsumer(final HttpClientConfig config) {
    super(config);
    this.config = config;
    this.subscribeInfoManager = new SubscribeInfoManager();
    this.offsetStorage = new MysqlOffsetStorage(config.getDataSource());
    this.recoverStorageManager = new RecoverStorageManager(new MetaClientConfig(), this.subscribeInfoManager);
    this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override/*  w  ww  .j av a2 s.c o  m*/
        public void run() {
            SimpleHttpConsumer.this.commitOffsets();
        }
    }, config.getCommitOffsetPeriodInMills(), config.getCommitOffsetPeriodInMills(), TimeUnit.MILLISECONDS);
    this.fetchManager = new SimpleFetchManager(config, this);
    this.fetchManager.resetFetchState();
}

From source file:com.oneops.metrics.OneOpsMetrics.java

private void addIbatisMetrics() {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    int initialDelay = 10;
    //scheduled with ibatis
    //getMap and register all meters with id and avg time .
    Runnable registerMetrics = () -> {
        Map<String, Stats> metrics = StatsPlugin.getStatsMap();
        try {//  w  w w  . j  a va  2 s  .c o m
            final SortedSet<String> registeredMetrics = ooMetricsRegistry.getNames();
            final long count = metrics.entrySet().parallelStream().map((e) -> {
                Meter m = ooMetricsRegistry.meter(e.getKey());
                if (m.getCount() != e.getValue().getNoOfCalls()) {
                    ooMetricsRegistry.meter(e.getKey()).mark(e.getValue().getNoOfCalls() - m.getCount());
                }
                if (!registeredMetrics.contains(e.getKey() + "_avg")) {
                    ooMetricsRegistry.register(e.getKey() + "_avg", (Gauge<Double>) e.getValue()::getAverage);
                }
                if (!registeredMetrics.contains(e.getKey() + "_max")) {
                    ooMetricsRegistry.register(e.getKey() + "_max", (Gauge<Long>) e.getValue()::getMaxTime);
                }
                return 1;
            }).count();

        } catch (Exception e) {
            logger.warn("There was an error in reporting metrics", e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Finished reporting metrics for ibatis" + metrics.size());
        }
    };

    executor.scheduleAtFixedRate(registerMetrics, initialDelay, 60, TimeUnit.SECONDS);
}

From source file:com.ctrip.infosec.rule.executor.ModelRulesExecutorService.java

@PostConstruct
public void dequeue() {
    int threads = 1;
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    for (int i = 0; i < threads; i++) {
        executor.submit(new Runnable() {
            @Override/*from   w  w w  . j a  v  a 2s .  c om*/
            public void run() {
                while (true) {
                    RiskFact fact = null;
                    beforeInvoke("ModelRules.execute");
                    try {
                        fact = queue.take();
                        TraceLogger.beginTrans(fact.eventId);
                        TraceLogger.setParentTransId(
                                valueAsString(fact.ext, Constants.key_traceLoggerParentTransId));
                        fact.ext.remove(Constants.key_traceLoggerParentTransId);
                        execute(fact);
                    } catch (Exception ex) {
                        fault("ModelRules.execute");
                        logger.error("dequeue exception.", ex);
                    } finally {
                        afterInvoke("ModelRules.execute");
                        if (fact != null) {
                            TraceLogger.commitTrans();
                        }
                        Threads.sleep(10, TimeUnit.MILLISECONDS);
                    }
                }
            }
        });
    }
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            int size = queue.size();
            if (size > 0) {
                SarsMqStatRepository.put("MODEL_EXECUTE_QUEUE", size);
                logger.warn("queue size: " + size);
            }
            int max = 10000;
            if (size > max) {
                do {
                    RiskFact fact = queue.poll();
                    logger.warn("model queue is full. drop message: " + fact.eventId);
                } while (queue.size() > max);
            }
        }
    }, 30, 30, TimeUnit.SECONDS);
}

From source file:au.com.smarttrace.beacons.BluetoothService.java

@Override
public void onCreate() {
    super.onCreate();
    initBluetooth();// w  w w.  jav a 2 s  .  co  m
    binder = new LocalBinder();
    scanning = false;
    executor = Executors.newSingleThreadScheduledExecutor();
}

From source file:com.google.pubsub.clients.common.MetricsHandler.java

MetricsHandler(String project, String clientType, MetricName metricName) {
    this.project = project;
    this.clientType = clientType;
    this.metricName = metricName;
    dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    distribution = new LatencyDistribution();
    monitoredResource = new MonitoredResource().setType("gce_instance");
    executor = Executors.newSingleThreadScheduledExecutor();
    executor.execute(this::initialize);
}