Example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

List of usage examples for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledExecutorService scheduleAtFixedRate.

Prototype

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

Source Link

Document

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay , then initialDelay + period , then initialDelay + 2 * period , and so on.

Usage

From source file:app.screen.MyActivity.java

/** create a repeating executor that displays debug messages after interacting with service */
private void _scheduleRepeatingTask() {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            try {
                StringBuilder sb = new StringBuilder();
                sb.append("ScheduledExecutorRunning - ").append(new Date().toString());
                AndroidUtils.log(IconPaths.MyApp, sb.toString());
            } catch (Exception e) {
            }/*from  www .j  a  v  a 2  s  .co m*/
        }
    }, 0, MyActivityRepeatDelay_ms, TimeUnit.MILLISECONDS);
    lifecycleHelper.addResource(executor);
}

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

/**
 * {@inheritDoc}/*from  w ww  .  j a  v a2  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:com.hurence.logisland.connect.opc.ua.OpcUaSourceTaskTest.java

@Test
@Ignore// w  w w . j  av  a 2 s  .  c  o m
public void e2eTest() throws Exception {
    OpcUaSourceConnector connector = new OpcUaSourceConnector();
    Map<String, String> properties = new HashMap<>();
    properties.put(OpcUaSourceConnector.PROPERTY_AUTH_BASIC_USER, "test");
    properties.put(OpcUaSourceConnector.PROPERTY_AUTH_BASIC_PASSWORD, "test");
    properties.put(CommonDefinitions.PROPERTY_CONNECTION_SOCKET_TIMEOUT, "10000");
    properties.put(CommonDefinitions.PROPERTY_SERVER_URI, "opc.tcp://127.0.0.1:53530/OPCUA/SimulationServer");
    properties.put(CommonDefinitions.PROPERTY_TAGS_ID, "ns=5;s=Counter1,ns=5;s=Random1,ns=5;s=Sinusoid1");
    properties.put(CommonDefinitions.PROPERTY_TAGS_STREAM_MODE, "SUBSCRIBE,POLL,SUBSCRIBE");
    properties.put(CommonDefinitions.PROPERTY_TAGS_SAMPLING_RATE, "PT3S,PT0.01S,PT1S");
    properties.put(OpcUaSourceConnector.PROPERTY_DATA_PUBLICATION_RATE, "PT1S");

    connector.start(properties);
    OpcUaSourceTask task = new OpcUaSourceTask();
    task.start(connector.taskConfigs(1).get(0));
    ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
    Gson json = new Gson();
    es.scheduleAtFixedRate(() -> {
        try {
            task.poll().stream()
                    .map(a -> Pair.of(new Date((Long) a.sourceOffset().get(OpcRecordFields.SAMPLED_TIMESTAMP)),
                            json.toJson(a)))
                    .forEach(System.out::println);
        } catch (InterruptedException e) {
            //do nothing
        }
    }, 0, 10, TimeUnit.MILLISECONDS);

    Thread.sleep(600000);
    task.stop();
    es.shutdown();
    connector.stop();
}

From source file:org.xdi.oxd.server.license.LicenseService.java

private void schedulePeriodicValidation() {
    final ScheduledExecutorService executorService = Executors
            .newSingleThreadScheduledExecutor(CoreUtils.daemonThreadFactory());
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override//from   w ww.j  a  v  a  2 s. co  m
        public void run() {
            licenseValid = validate();
        }
    }, 1, 24, TimeUnit.HOURS);
}

From source file:com.talis.hadoop.rdf.merge.IndexMergeReducer.java

@Override
public void reduce(LongWritable key, Iterable<Text> value, final Context context)
        throws IOException, InterruptedException {
    Runnable reporter = new Runnable() {
        @Override/*  w w w .  j  a v  a2  s .c o m*/
        public void run() {
            context.progress();
        }
    };
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(reporter, 60, 60, TimeUnit.SECONDS);
    LOG.debug("Scheduled progress reporter, combining index shards");

    FileSystem shardsFs = null;
    for (Text remoteShard : value) {
        Path remote = new Path(remoteShard.toString());
        if (null == shardsFs) {
            shardsFs = FileSystem.get(remote.toUri(), context.getConfiguration());
        }
        LOG.debug("Copying shard from {} to {}", remote, localShards);
        shardsFs.copyToLocalFile(remote, localShards);
        LOG.debug("Copy complete");
    }

    Directory[] shards = getDirectories();
    LOG.debug("About to combine {} shards", shards.length);
    writer.addIndexesNoOptimize(shards);
    LOG.debug("Combined index built, terminating reporter");
    task.cancel(true);

}

From source file:org.pentaho.di.www.ge.trans.LogBrowser.java

public void installLogSniffer() {
    // Create a new buffer appender to the log and capture that directly...
    ///*ww w  .j a v  a 2s. c  o  m*/
    lastLogId = new AtomicInteger(-1);
    busy = new AtomicBoolean(false);
    logLayout = new KettleLogLayout(true);

    /*
     * final StyleRange normalLogLineStyle = new StyleRange();
     * normalLogLineStyle.foreground =
     * GUIResource.getInstance().getColorBlue(); final StyleRange
     * errorLogLineStyle = new StyleRange(); errorLogLineStyle.foreground =
     * GUIResource.getInstance().getColorRed();
     */

    // Refresh the log every second or so
    //
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    logRefreshTimerFuture = scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            busy.set(true);
            System.out.println(String.format("Running LogDelegate refreshLog()"));
            new Thread(new Runnable() {
                public void run() {
                    collectAndPushishLog();
                }
            }).start();
            busy.set(false);
        }
    }, 1000, 500, TimeUnit.MILLISECONDS);
}

From source file:hivemall.mix.server.MixServer.java

public void start() throws CertificateException, SSLException, InterruptedException {
    // Configure SSL.
    final SslContext sslCtx;
    if (ssl) {// w w  w  . j  a  va2  s.  co m
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    } else {
        sslCtx = null;
    }

    // configure metrics
    ScheduledExecutorService metricCollector = Executors.newScheduledThreadPool(1);
    MixServerMetrics metrics = new MixServerMetrics();
    ThroughputCounter throughputCounter = new ThroughputCounter(metricCollector, 5000L, metrics);
    if (jmx) {// register mbean
        MetricsRegistry.registerMBeans(metrics, port);
    }

    // configure initializer
    SessionStore sessionStore = new SessionStore();
    MixServerHandler msgHandler = new MixServerHandler(sessionStore, syncThreshold, scale);
    MixServerInitializer initializer = new MixServerInitializer(msgHandler, throughputCounter, sslCtx);

    Runnable cleanSessionTask = new IdleSessionSweeper(sessionStore, sessionTTLinSec * 1000L);
    ScheduledExecutorService idleSessionChecker = Executors.newScheduledThreadPool(1);
    try {
        // start idle session sweeper
        idleSessionChecker.scheduleAtFixedRate(cleanSessionTask, sessionTTLinSec + 10L, sweepIntervalInSec,
                TimeUnit.SECONDS);
        // accept connections
        acceptConnections(initializer, port, numWorkers);
    } finally {
        // release threads
        idleSessionChecker.shutdownNow();
        if (jmx) {
            MetricsRegistry.unregisterMBeans(port);
        }
        metricCollector.shutdownNow();
    }
}

From source file:com.ning.metrics.eventtracker.ScribeSender.java

public ScribeSender(ScribeClient scribeClient, int messagesToSendBeforeReconnecting, int maxIdleTimeInMinutes) {
    this.scribeClient = scribeClient;
    this.messagesToSendBeforeReconnecting = messagesToSendBeforeReconnecting;

    // Setup a watchdog for the Scribe connection. We don't want to keep it open forever. For instance, SLB VIP
    // may trigger a RST if idle more than a few minutes.
    final ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1,
            Executors.defaultThreadFactory());
    executor.scheduleAtFixedRate(new Runnable() {
        @Override/*from   w  ww  .j  av  a2s .  com*/
        public void run() {
            if (sleeping.get()) {
                log.info("Idle connection to Scribe, re-opening it");
                createConnection();
            }
            sleeping.set(true);
        }
    }, maxIdleTimeInMinutes, maxIdleTimeInMinutes, TimeUnit.MINUTES);
}

From source file:org.openremote.controller.protocol.isy99.Isy99StatusReader.java

/**
  * @param host       hostname or IP address for the ISY-99
  * @param username   username for authentication to the ISY-99
  * @param password   password for authentication to the ISY-99
  */// ww  w . j  a  va  2  s .c  om
public Isy99StatusReader(String host, String username, String password) {
    Runnable queryTask = new QueryTask(host, username, password);

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NUM_THREADS);
    scheduler.scheduleAtFixedRate(queryTask, INITIAL_DELAY, PERIOD_BETWEEN_EXECUTIONS, TimeUnit.SECONDS);
}

From source file:com.web.server.util.FarmWarFileTransfer.java

private FarmWarFileTransfer(String deployDir, String farmwarDir, String clusterGroup) {
    this.deployDir = deployDir;
    this.farmwarDir = farmwarDir;
    this.clusterGroup = clusterGroup;
    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    FarmWarDirWatcher task = new FarmWarDirWatcher(farmwarDir, this);
    exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
}