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:ecg.ecgshow.ECGShowUI.java

private void createHeartRateData(long timeZone) {
    HeartRatedatas = new short[2];
    HeartRateData = new JPanel();
    //HeartRateData.setLayout(new BorderLayout());
    HeartRateData.setLayout(new FlowLayout());
    HeartRateData.setBounds(0, 0, (int) (WIDTH * 0.14), (int) (HEIGHT * 0.15));
    HeartRateData.setBackground(Color.BLACK);

    JLabel jLabel1 = new JLabel("---");
    if (HeartRatedatas[0] == 0x00 || HeartRatedatas == null) {
        jLabel1.setText("---");
    } else {/*  ww  w.j  a va2 s. c o m*/
        jLabel1.setText(Short.toString((short) HeartRatedatas[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(" bpm");
    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); //??

    HeartRateData.add(jLabelName);
    HeartRateData.add(jLabel1);
    HeartRateData.add(jLabelUnit);
    System.out.println("HeartRatedatas" + Short.toString(HeartRatedatas[0]));
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (HeartRatedatas[0] == -100 || HeartRatedatas[0] == 156 || HeartRatedatas[0] == 0) {
                jLabel1.setText("--");
            } else {
                jLabel1.setText(String.valueOf(HeartRatedatas[0]));
            }
            HeartRateData.repaint();
        }
    }, 0, 3, TimeUnit.SECONDS);
}

From source file:org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean.java

/**
 * Register the specified {@link ScheduledExecutorTask ScheduledExecutorTasks}
 * on the given {@link ScheduledExecutorService}.
 * @param tasks the specified ScheduledExecutorTasks (never empty)
 * @param executor the ScheduledExecutorService to register the tasks on.
 *//*from  w  w  w .  j ava2 s .co  m*/
protected void registerTasks(ScheduledExecutorTask[] tasks, ScheduledExecutorService executor) {
    for (int i = 0; i < tasks.length; i++) {
        ScheduledExecutorTask task = tasks[i];
        Runnable runnable = getRunnableToSchedule(task);
        if (task.isOneTimeTask()) {
            executor.schedule(runnable, task.getDelay(), task.getTimeUnit());
        } else {
            if (task.isFixedRate()) {
                executor.scheduleAtFixedRate(runnable, task.getDelay(), task.getPeriod(), task.getTimeUnit());
            } else {
                executor.scheduleWithFixedDelay(runnable, task.getDelay(), task.getPeriod(),
                        task.getTimeUnit());
            }
        }
    }
}

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

private void runMultithreadedBenchmark(LoadAwareCustomStreamGrouping grouper, List<Integer> availableTaskIds,
        LoadMapping loadMapping, int numThreads) throws InterruptedException, ExecutionException {
    // Task Id not used, so just pick a static value
    final int inputTaskId = 100;

    final WorkerTopologyContext context = mockContext(availableTaskIds);

    // Call prepare with our available taskIds
    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;//from  ww w  .j a v a 2  s .  c om
    while (true) {
        grouper.chooseTasks(inputTaskId, Lists.newArrayList());

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

    final int groupingExecutionsPerThread = 2_000_000_000;

    List<Callable<Long>> threadTasks = Lists.newArrayList();
    for (int x = 0; x < numThreads; x++) {
        Callable<Long> threadTask = new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                long current = System.currentTimeMillis();
                for (int i = 1; i <= groupingExecutionsPerThread; i++) {
                    grouper.chooseTasks(inputTaskId, Lists.newArrayList());
                }
                return System.currentTimeMillis() - current;
            }
        };

        // Add to our collection.
        threadTasks.add(threadTask);
    }

    ExecutorService executor = Executors.newFixedThreadPool(threadTasks.size());
    List<Future<Long>> taskResults = executor.invokeAll(threadTasks);

    // Wait for all tasks to complete
    Long maxDurationMillis = 0L;
    for (Future taskResult : taskResults) {
        while (!taskResult.isDone()) {
            Thread.sleep(100);
        }
        Long durationMillis = (Long) taskResult.get();
        if (maxDurationMillis < durationMillis) {
            maxDurationMillis = durationMillis;
        }
    }

    LOG.info("Max duration among threads is : {} ms", maxDurationMillis);

    refreshService.shutdownNow();
}

From source file:org.apache.storm.metric.FileBasedEventLogger.java

private void setUpFlushTask() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    Runnable task = new Runnable() {
        @Override// w w w .  j ava2  s.c om
        public void run() {
            try {
                if (dirty) {
                    eventLogWriter.flush();
                    dirty = false;
                }
            } catch (IOException ex) {
                LOG.error("Error flushing " + eventLogPath, ex);
                throw new RuntimeException(ex);
            }
        }
    };

    scheduler.scheduleAtFixedRate(task, FLUSH_INTERVAL_MILLIS, FLUSH_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
}

From source file:org.apache.synapse.commons.throttle.core.ThrottleContextCleanupTask.java

public ThrottleContextCleanupTask() {

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("Throttle Cleanup Task");
            return t;
        }//from w  ww  .j a  v  a2 s  .  c  o  m
    });

    String throttleFrequency = System.getProperty(THROTTLE_CONTEXT_CLEANUP_TASK_FREQUENCY);
    if (throttleFrequency == null) {
        throttleFrequency = "3600000";
    }

    if (log.isDebugEnabled()) {
        log.debug("Throttling Cleanup Task Frequency set to " + throttleFrequency);
    }

    executor.scheduleAtFixedRate(new CleanupTask(), Integer.parseInt(throttleFrequency),
            Integer.parseInt(throttleFrequency), TimeUnit.MILLISECONDS);

}

From source file:com.jose.castsocialconnector.main.MainActivity.java

private void startCheckNewDataService() {
    ScheduledExecutorService scheduleCheckMessagesTaskExecutor;
    scheduleCheckMessagesTaskExecutor = Executors.newScheduledThreadPool(5);
    if (!Config.DEBUG)
        newPhotosSchedule = scheduleCheckMessagesTaskExecutor
                .scheduleAtFixedRate(newPhotosService.getRunnable(), 0, 1, TimeUnit.MINUTES);
}

From source file:fr.tpt.atlanalyser.examples.ExampleRunner.java

public void executePost2Pre(File postFile, int maxNumRuleIterations) throws IOException {
    // checkDirs();
    inputMM = getInputMMEPkg();//w w  w .  jav  a 2 s.  c o  m
    outputMM = getOutputMMEPkg();
    makeAbstractClassesInstantiable(inputMM);
    makeAbstractClassesInstantiable(outputMM);
    Module transfo = loadHenshinTransformation();

    EcoreUtil.resolveAll(transfo);

    EPackage traceMM = resourceSet.getPackageRegistry().getEPackage("http://traces/1.0");

    stripFromAttributes(transfo);

    Resource postRes = resourceSet.getResource(URI.createFileURI(postFile.getCanonicalPath()), true);
    Module postModule = (Module) postRes.getContents().get(0);
    EList<Unit> units = postModule.getUnits();
    List<Formula> postconditions = Lists.transform(units, new Function<Unit, Formula>() {
        @Override
        public Formula apply(Unit arg0) {
            return ((Rule) arg0).getLhs().getFormula();
        }
    });

    Module preModule = HenshinFactory.eINSTANCE.createModule();
    preModule.setName("Preconditions");

    LOGGER.info("Starting Post2Pre for {}", transfo.getName());

    Post2Pre4ATL post2Pre = new Post2Pre4ATL(transfo, inputMM, outputMM, traceMM, jobs);

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

        private final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        private final Logger LOGGER = LogManager.getLogger("MemMon");

        @Override
        public void run() {
            // LOGGER.setAdditivity(false);

            // for (Enumeration iterator =
            // AGGWrapper.LOGGER.getAllAppenders(); iterator
            // .hasMoreElements();) {
            // Appender appender = (Appender) iterator.nextElement();
            // LOGGER.addAppender(appender);
            // }

            MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
            final long used = heapUsage.getUsed();
            double usedGB = (double) used / (1 << 30);
            final long max = heapUsage.getMax();
            double maxGB = (double) max / (1 << 30);
            LOGGER.info(String.format("Memory use : %6.3fGB of %6.3fGB (%.2f%%)", usedGB, maxGB,
                    (float) used / max * 100));
        }
    }, 0, 10, TimeUnit.SECONDS);

    try {
        for (Formula formula : postconditions) {
            Formula pre = post2Pre.post2Pre(formula, maxNumRuleIterations);
            Rule preRule = HenshinFactory.eINSTANCE.createRule();
            Graph preLhs = HenshinFactory.eINSTANCE.createGraph();
            preLhs.setFormula(EcoreUtil.copy(pre));
            preRule.setLhs(preLhs);
            preModule.getUnits().add(preRule);
        }
    } finally {
        memMonitorExecutor.shutdown();
    }

    File outputDir = new File(baseDir, "Preconditions");
    if (!outputDir.isDirectory()) {
        outputDir.mkdir();
    }

    Resource outputRes = resourceSet
            .createResource(URI.createFileURI("Preconditions/" + postFile.getName() + "_pre.henshin"));

    outputRes.getContents().add(preModule);

    LOGGER.info("Writing Precondition in {}", outputRes.getURI().toString());
    outputRes.save(xmiSaveOptions);

    LOGGER.info("Done!");
}

From source file:com.brucegiese.perfectposture.OrientationService.java

/**
 * Start monitoring the user's posture.//from w  ww  .j a  v a 2s . c o  m
 */
private void startChecking() {
    mChinTuckReminderCounter = 0;
    mCurrentPostureGood = true; // start out assuming good posture
    mHysteresisCounter = 0;
    mBadPostureReminderCounter = 0;

    try {
        if (mOrientation.startOrienting()) {
            OrientationService.sIsRunning = true;

            if (mScheduledFuture == null) {
                // We use an additional thread for the periodic execution task.

                ScheduledExecutorService mScheduler = Executors.newScheduledThreadPool(1);
                mScheduledFuture = mScheduler.scheduleAtFixedRate(mDoPeriodicWork, UPDATE_INTERVAL,
                        UPDATE_INTERVAL, TimeUnit.SECONDS);
            } else {
                Log.e(TAG, "startChecking() was called when checking was already running");
            }
        } else {
            Toast.makeText(this, R.string.no_sensors, Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception when starting orientation and scheduler: ", e);
    }

    // Register the broadcast receiver
    IntentFilter iFilter = new IntentFilter();
    iFilter.addAction(TURN_OFF_SERVICE_ACTION);
    LocalBroadcastManager.getInstance(this).registerReceiver(mCommandReceiver, iFilter);
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.PairingManagerImpl.java

public PairingManagerImpl(DeviceManager deviceManager,
        /*LicenseManager licenseManager,*/ EventGate eventGateToHigherAbstractionModelLevels,
        ScheduledExecutorService executorService, String pemUID) {
    pairingMode = false;/*w  w w . jav  a 2 s. co m*/
    this.pemUID = pemUID;
    toPair = Collections.synchronizedMap(new HashMap<String, PairingEntry>());
    executorService.scheduleAtFixedRate(new CleaningThread(), CLEANING_THREAD_SLEEPING_PERIOD,
            CLEANING_THREAD_SLEEPING_PERIOD, TimeUnit.MINUTES);

    this.deviceManager = deviceManager;
    //this.licenseManager = licenseManager;
    this.eventGateToHigherAbstractionModelLevels = eventGateToHigherAbstractionModelLevels;
    eventGateToHigherAbstractionModelLevels.addListener(this);
}