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:io.soabase.core.SoaBundle.java

private void startDiscoveryHealth(SoaDiscovery discovery, SoaConfiguration soaConfiguration,
        Environment environment) {
    SoaDiscoveryHealth discoveryHealth = checkManaged(environment,
            soaConfiguration.getDiscoveryHealthFactory().build(soaConfiguration, environment));
    ScheduledExecutorService service = environment.lifecycle()
            .scheduledExecutorService("DiscoveryHealthChecker-%d").build();
    service.scheduleAtFixedRate(
            new HealthCheckIntegration(environment.healthChecks(), discovery, discoveryHealth),
            soaConfiguration.getDiscoveryHealthCheckPeriodMs(),
            soaConfiguration.getDiscoveryHealthCheckPeriodMs(), TimeUnit.MILLISECONDS);
}

From source file:net.sf.mpaxs.spi.computeHost.Host.java

/**
 * Meldet diesen Host beim Masterserver an. Nach erfolgreicher Anmeldung
 * kann der Masterserver Jobs an diesen Host vergeben.
 *///from  w  w  w  .j av  a2s. c  om
private void connectToMasterServer() {
    final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    final long startUpAt = System.currentTimeMillis();
    final long failAfter = 5000;
    ses.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            Logger.getLogger(Host.class.getName()).log(Level.FINE,
                    "Trying to connect to MasterServer from IP " + settings.getLocalIp());
            long currentTime = System.currentTimeMillis();
            if (currentTime - startUpAt >= failAfter) {
                Logger.getLogger(Host.class.getName()).log(Level.WARNING,
                        "Waited {0} seconds for MasterServer, shutting down ComputeHost", (failAfter / 1000));
                System.exit(1);
            }
            try {
                Logger.getLogger(Host.class.getName()).log(Level.FINE,
                        "Trying to bind to MasterServer at " + settings.getMasterServerIP() + ":"
                                + settings.getMasterServerPort() + " with name: "
                                + settings.getMasterServerName());
                IRemoteServer remRef = (IRemoteServer) Naming.lookup("//" + settings.getMasterServerIP() + ":"
                        + settings.getMasterServerPort() + "/" + settings.getMasterServerName());
                settings.setRemoteReference(remRef);
                UUID hostID = remRef.addHost(authToken, settings.getName(), settings.getLocalIp(),
                        settings.getCores());
                settings.setHostID(hostID);
                Logger.getLogger(Host.class.getName()).log(Level.FINE, "Connection to server established!");
                ses.shutdown();
                try {
                    ses.awaitTermination(5, TimeUnit.SECONDS);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (NotBoundException ex) {
                Logger.getLogger(Host.class.getName()).log(Level.INFO,
                        "Master server not found, waiting for connection!");
                //Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
            } catch (MalformedURLException ex) {
                Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
                System.exit(1);
            } catch (RemoteException ex) {
                Logger.getLogger(Host.class.getName()).log(Level.SEVERE, null, ex);
                System.exit(1);
            }
        }
    }, 1, settings.getMasterServerTimeout(), TimeUnit.SECONDS);

}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testNewSingleThreadScheduledExecutor() {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(threadFactory);

    ScheduledFuture<?> future1 = executor.schedule(new NullRunnable(), 10, TimeUnit.MILLISECONDS);
    ScheduledFuture<Integer> future2 = executor.schedule(new IntCallable(1), 10, TimeUnit.MILLISECONDS);
    ScheduledFuture<?> future3 = executor.scheduleAtFixedRate(new NullRunnable(), 10, 10,
            TimeUnit.MILLISECONDS);
    ScheduledFuture<?> future4 = executor.scheduleWithFixedDelay(new NullRunnable(), 10, 10,
            TimeUnit.MILLISECONDS);

    List<Runnable> notRun = executor.shutdownNow();
    Assert.assertTrue(executor.isShutdown());
    Assert.assertEquals(4, notRun.size());
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future1));
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future2));
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future3));
    Assert.assertTrue(CollectionUtils.containsInstance(notRun, future4));
}

From source file:com.janrain.backplane.server.config.BackplaneConfig.java

private ScheduledExecutorService createCleanupTask() {
    long cleanupIntervalMinutes;
    logger.info("calling createCleanupTask()");
    try {/*  w w  w . j  av  a 2 s. c  o  m*/
        cleanupIntervalMinutes = Long.valueOf(cachedGet(BpServerProperty.CLEANUP_INTERVAL_MINUTES));
    } catch (SimpleDBException e) {
        throw new RuntimeException("Error getting server property " + BpServerProperty.CLEANUP_INTERVAL_MINUTES,
                e);
    }

    ScheduledExecutorService cleanupTask = Executors.newScheduledThreadPool(1);
    cleanupTask.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {

            compileMetrics();

            try {
                getMessagesTime.time(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        deleteExpiredMessages();
                        return null;
                    }
                });
            } catch (Exception e) {
                logger.error("Error while cleaning up expired messages, " + e.getMessage(), e);
            }

        }

    }, cleanupIntervalMinutes, cleanupIntervalMinutes, TimeUnit.MINUTES);

    return cleanupTask;
}

From source file:scouter.plugin.server.alert.email.EmailPlugin.java

public EmailPlugin() {
    if (ai.incrementAndGet() == 1) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        //thread count check
        executor.scheduleAtFixedRate(new Runnable() {
            @Override//from   w  ww.java  2s . c om
            public void run() {
                for (int objHash : javaeeObjHashList) {
                    try {
                        if (AgentManager.isActive(objHash)) {
                            ObjectPack objectPack = AgentManager.getAgent(objHash);
                            MapPack mapPack = new MapPack();
                            mapPack.put("objHash", objHash);
                            mapPack = AgentCall.call(objectPack, RequestCmd.OBJECT_THREAD_LIST, mapPack);

                            final int LIMIT = 30; //?  . ? 20 ?    30 ? ?

                            //  .   ?  thread exceed threshold  ?? .
                            int threadCountThreshold = conf.getInt("ext_plugin_thread_count_threshold", LIMIT);
                            int threadCount = mapPack.getList("name").size();

                            /*   ? */
                            if (threadCountThreshold != 0 && threadCount > threadCountThreshold) {
                                AlertPack ap = new AlertPack();

                                //  ? 2  FATAL, ? WARN
                                if (threadCount > threadCountThreshold * 2)
                                    ap.level = AlertLevel.FATAL;
                                else
                                    ap.level = AlertLevel.WARN;

                                ap.objHash = objHash;
                                ap.title = "  !";
                                ap.message = objectPack.objName + "?   " + threadCount
                                        + ", (" + LIMIT + ") !";
                                ap.time = System.currentTimeMillis();
                                ap.objType = objectPack.objType;

                                long limitTime = conf.getLong("ext_plugin_thread_limit_time", 120000); //2
                                long safeTime = conf.getLong("ext_plugin_thread_safe_time", 180000); //3

                                //? ? objectPack.objName ? 
                                if (objectContainer.sendAlert(ap, objectPack.objName, limitTime, safeTime))
                                    alert(ap);
                            }
                        }
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }, 0, 5, TimeUnit.SECONDS); //5 
    }
}

From source file:com.srotya.monitoring.kafka.util.KafkaConsumerOffsetUtil.java

public void setupMonitoring() {
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    executorService.scheduleAtFixedRate(new KafkaConsumerOffsetThread(), 2,
            kafkaConfiguration.getRefreshSeconds(), TimeUnit.SECONDS);
    log.info("Monitoring thread for zookeeper offsets online");
}

From source file:com.mmj.app.biz.service.impl.UserServiceImpl.java

@PostConstruct
public void cronCache() {
    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);
    newScheduledThreadPool.scheduleAtFixedRate(new Runnable() {

        @Override/*from  w  w w  .  j a v a 2s .c  o  m*/
        public void run() {
            try {
                init();
            } catch (Throwable e) {
                logger.error("init memberCacheMap error", e);
            }
        }

    }, 50, 12 * 60 * 60, TimeUnit.SECONDS);
}

From source file:com.zb.app.biz.service.impl.TravelCompanyServiceImpl.java

@PostConstruct
public void cronCache() {
    Result companyRegist = notifyService.regist(new NotifyListener() {

        @EventConfig(events = { EventType.companyAdd, EventType.companyDelete, EventType.companyUpdate })
        public void companyEvent(CompanyEvent event) {
            handle(event);//  ww  w  . j  ava 2 s  .  co  m
        }
    });
    if (companyRegist.isFailed()) {
        logger.error("TravelCompanyServiceImpl init companyRegist ?failed!");
    } else {
        logger.error("TravelCompanyServiceImpl init companyRegist ?success!");
    }

    ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(1);
    newScheduledThreadPool.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            try {
                init();
            } catch (Throwable e) {
                logger.error("init travelCompanyCacheMap error", e);
            }
        }

    }, 0, 12, TimeUnit.HOURS);
}

From source file:org.apache.storm.grouping.LoadAwareShuffleGroupingTest.java

private void runSimpleBenchmark(LoadAwareCustomStreamGrouping grouper, List<Integer> availableTaskIds,
        LoadMapping loadMapping) {/* w w  w  .ja v  a 2  s .  c  om*/
    // Task Id not used, so just pick a static value
    final int inputTaskId = 100;

    WorkerTopologyContext context = mockContext(availableTaskIds);
    grouper.prepare(context, null, availableTaskIds);

    // periodically calls refreshLoad in 1 sec to simulate worker load update timer
    ScheduledExecutorService refreshService = MoreExecutors
            .getExitingScheduledExecutorService(new ScheduledThreadPoolExecutor(1));
    refreshService.scheduleAtFixedRate(() -> grouper.refreshLoad(loadMapping), 1, 1, TimeUnit.SECONDS);

    long current = System.currentTimeMillis();
    int idx = 0;
    while (true) {
        grouper.chooseTasks(inputTaskId, Lists.newArrayList());

        idx++;
        if (idx % 100000 == 0) {
            // warm up 60 seconds
            if (System.currentTimeMillis() - current >= 60_000) {
                break;
            }
        }
    }

    current = System.currentTimeMillis();
    for (int i = 1; i <= 2_000_000_000; i++) {
        grouper.chooseTasks(inputTaskId, Lists.newArrayList());
    }

    LOG.info("Duration: {} ms", (System.currentTimeMillis() - current));

    refreshService.shutdownNow();
}

From source file:ecg.ecgshow.ECGShowUI.java

private void createBloodOxygenData(long timeZone) {
    BloodOxygendatas = new short[2];
    BloodOxygenData = new JPanel();
    BloodOxygenData.setLayout(new FlowLayout());
    BloodOxygenData.setBounds(0, 0, (int) (WIDTH * 0.14), (int) (HEIGHT * 0.15));
    BloodOxygenData.setBackground(Color.BLACK);

    JLabel jLabel1 = new JLabel("---");
    if (BloodOxygendatas[0] == 0x00 || BloodOxygendatas == null) {
        jLabel1.setText("---");
    } else {//from  w w w  .  j ava  2s .com
        jLabel1.setText(Short.toString((short) BloodOxygendatas[0]));
    }
    System.out.println("BloodOxygendatas" + Short.toString(BloodOxygendatas[0]));
    jLabel1.setFont(loadFont("LED.tff", (float) (HEIGHT * 0.070)));
    jLabel1.setBackground(Color.BLACK);
    jLabel1.setForeground(Color.GREEN);
    jLabel1.setBounds(0, 0, 100, 100);
    jLabel1.setOpaque(true);

    JLabel jLabelName = new JLabel(" ");
    jLabelName.setFont(new Font("SansSerif", 0, (int) (HEIGHT * 0.020)));
    jLabelName.setBackground(Color.BLACK);
    jLabelName.setForeground(new Color(237, 65, 43));
    jLabelName.setBounds(0, 0, 100, 100);
    jLabelName.setOpaque(true); //??

    JLabel jLabelUnit = new JLabel(" %");
    jLabelUnit.setFont(new Font("SansSerif", 0, (int) (HEIGHT * 0.020)));
    jLabelUnit.setBackground(Color.BLACK);
    jLabelUnit.setForeground(Color.GREEN);
    jLabelUnit.setBounds(0, 0, 100, 100);
    jLabelUnit.setOpaque(true); //??

    BloodOxygenData.add(jLabelName);
    BloodOxygenData.add(jLabel1);
    BloodOxygenData.add(jLabelUnit);

    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (BloodOxygendatas[0] == 0 || HeartRatedatas[0] == -100) {
                jLabel1.setText("--");
            } else {
                jLabel1.setText(String.valueOf(BloodOxygendatas[0]));
            }
            BloodOxygenData.repaint();
        }
    }, 0, 3, TimeUnit.SECONDS);
}