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:org.wso2.andes.kernel.MessageFlusher.java

/**
 * Initialize the delivery filter chain//from  www .  ja va2s. co  m
 */
private void initializeDeliveryResponsibilityComponents() {
    //assign the head of the handler chain
    deliveryResponsibilityHead = new PurgedMessageHandler();
    ExpiredMessageHandler expiredMessageHandler = new ExpiredMessageHandler();
    //link the second handler to the head
    deliveryResponsibilityHead.setNextDeliveryFilter(expiredMessageHandler);
    //link the third handler
    expiredMessageHandler.setNextDeliveryFilter(new DeliveryMessageHandler());

    int preDeliveryDeletionTaskScheduledPeriod = AndesConfigurationManager
            .readValue(AndesConfiguration.PERFORMANCE_TUNING_PRE_DELIVERY_EXPIRY_DELETION_INTERVAL);
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("ExpiryMessageDeletionTask-%d")
            .build();
    //executor service for pre delivery deletion task
    ScheduledExecutorService expiryMessageDeletionTaskScheduler = Executors
            .newSingleThreadScheduledExecutor(namedThreadFactory);
    //pre-delivery deletion task initialization
    PreDeliveryExpiryMessageDeletionTask preDeliveryExpiryMessageDeletionTask = new PreDeliveryExpiryMessageDeletionTask();
    //Set the expiry message deletion task to the expired message handler
    expiredMessageHandler.setExpiryMessageDeletionTask(preDeliveryExpiryMessageDeletionTask);
    //schedule the task at the specified intervals
    expiryMessageDeletionTaskScheduler.scheduleAtFixedRate(preDeliveryExpiryMessageDeletionTask,
            preDeliveryDeletionTaskScheduledPeriod, preDeliveryDeletionTaskScheduledPeriod, TimeUnit.SECONDS);

}

From source file:org.openhab.binding.network.service.NetworkService.java

public void startAutomaticRefresh(ScheduledExecutorService scheduledExecutorService,
        final StateUpdate stateUpdate) {
    Runnable runnable = new Runnable() {
        @Override//  www . ja  v  a2 s .  co m
        public void run() {
            try {
                stateUpdate.newState(updateDeviceState());
            } catch (InvalidConfigurationException e) {
                stateUpdate.invalidConfig();
            }
        }
    };

    refreshJob = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, refreshInterval,
            TimeUnit.MILLISECONDS);
}

From source file:org.dcache.xrootd.door.XrootdDoor.java

/**
 * Sets the ScheduledExecutorService used for periodic tasks.
 *//*from  w  ww  .j a  v  a2  s . c  o m*/
@Required
public void setExecutor(ScheduledExecutorService executor) {
    executor.scheduleAtFixedRate(new FireAndForgetTask(new PingMoversTask(_transfers.values())), PING_DELAY,
            PING_DELAY, TimeUnit.MILLISECONDS);
}

From source file:org.wso2.carbon.registry.eventing.RegistryEventDispatcher.java

public RegistryEventDispatcher() {
    digestQueues = new LinkedHashMap<String, Queue<DigestEntry>>();
    for (String s : new String[] { "h", "d", "w", "f", "m", "y" }) {
        //TODO: Identify Queuing mechanisms.
        digestQueues.put(s, new ConcurrentLinkedQueue<DigestEntry>());
    }/*from ww  w.  j  a v a2  s  . co m*/
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            GregorianCalendar utc = new GregorianCalendar(SimpleTimeZone.getTimeZone("UTC"));
            Map<String, List<DigestEntry>> digestEntries = new HashMap<String, List<DigestEntry>>();
            try {
                addToDigestEntryQueue(digestEntries, "h");
                if (utc.get(Calendar.HOUR_OF_DAY) == 0) {
                    addToDigestEntryQueue(digestEntries, "d");
                    if (utc.get(Calendar.DAY_OF_WEEK) == 1) {
                        addToDigestEntryQueue(digestEntries, "w");
                        if (utc.get(Calendar.WEEK_OF_YEAR) % 2 != 0) {
                            addToDigestEntryQueue(digestEntries, "f");
                        }
                    }
                    if (utc.get(Calendar.DAY_OF_MONTH) == 1) {
                        addToDigestEntryQueue(digestEntries, "m");
                        if (utc.get(Calendar.DAY_OF_YEAR) == 1) {
                            addToDigestEntryQueue(digestEntries, "y");

                        }
                    }
                }
                for (Map.Entry<String, List<DigestEntry>> e : digestEntries.entrySet()) {
                    List<DigestEntry> value = e.getValue();
                    Collections.sort(value, new Comparator<DigestEntry>() {
                        public int compare(DigestEntry o1, DigestEntry o2) {
                            if (o1.getTime() > o2.getTime()) {
                                return -1;
                            } else if (o1.getTime() < o2.getTime()) {
                                return 1;
                            }
                            return 0;
                        }
                    });
                    StringBuffer buffer = new StringBuffer();
                    for (DigestEntry entry : value) {
                        buffer.append(entry.getMessage()).append("\n\n");
                    }
                    RegistryEvent<String> re = new RegistryEvent<String>(buffer.toString());
                    re.setTopic(RegistryEvent.TOPIC_SEPARATOR + "DigestEvent");
                    DispatchEvent de = new DispatchEvent(re, e.getKey(), true);
                    Subscription subscription = new Subscription();
                    subscription.setTopicName(re.getTopic());
                    publishEvent(de, subscription, e.getKey(), true);
                }
            } catch (RuntimeException ignored) {
                // Eat any runtime exceptions that occurred, we don't care if the message went
                // or not.
            }
        }
    }, System.currentTimeMillis() % (1000 * 60 * 60), 1000 * 60 * 60, TimeUnit.MILLISECONDS);
    try {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                executorService.shutdownNow();
            }
        });
    } catch (IllegalStateException e) {
        executorService.shutdownNow();
        throw new IllegalStateException(
                "Unable to create registry event dispatcher during " + "shutdown process.");
    }
}

From source file:com.thinkbiganalytics.feedmgr.nifi.cache.NifiFlowCacheImpl.java

private void initExpireTimerThread() {
    long timer = 30; // run ever 30 sec to check and expire
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        checkAndExpireUnusedCache();//from w  w  w.j  a  v  a 2  s  .  co  m
    }, timer, timer, TimeUnit.SECONDS);

}

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

public ThrottleWindowReplicator() {

    String replicatorThreads = System.getProperty(WINDOW_REPLICATOR_POOL_SIZE);

    if (replicatorThreads != null) {
        replicatorPoolSize = Integer.parseInt(replicatorThreads);
    }// w w  w. jav  a2s  .  c  o  m

    if (log.isDebugEnabled()) {
        log.debug("Throttle window replicator pool size set to " + replicatorPoolSize);
    }

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(replicatorPoolSize,
            new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("Throttle window replicator - " + replicatorCount++);
                    return t;
                }
            });

    String windowReplicationFrequency = System.getProperty(WINDOW_REPLICATOR_FREQUENCY);
    if (windowReplicationFrequency == null) {
        windowReplicationFrequency = "50";
    }

    if (log.isDebugEnabled()) {
        log.debug("Throttling window replication frequency set to " + windowReplicationFrequency);
    }

    for (int i = 0; i < replicatorPoolSize; i++) {
        executor.scheduleAtFixedRate(new ReplicatorTask(), Integer.parseInt(windowReplicationFrequency),
                Integer.parseInt(windowReplicationFrequency), TimeUnit.MILLISECONDS);
    }
}

From source file:UserInterface.PDCPrimaryDoctorRole.PDCPrimaryDoctorReportsJPanel.java

private void generateReportToggleBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateReportToggleBtnActionPerformed
    // TODO add your handling code here:
    if (!generateReportToggleBtn.isSelected()) {
        reportJPanel.removeAll();//from w w w . j  a  v  a2s.  c om
        //reportJPanel.revalidate();
        reportJPanel.repaint();
        generateReportToggleBtn.setText("Generate Live Graph");
    } else {
        generateReportToggleBtn.setText("Stop Live Graph");
    }
    ScheduledExecutorService scheduledExecutorService2 = Executors.newScheduledThreadPool(5);

    Runnable task = new Runnable() {
        @Override
        public void run() {
            if (generateReportToggleBtn.isSelected()) {
                Patient patient = (Patient) patientListComboBox.getSelectedItem();
                String attribute = (String) vitalSignComboBox.getSelectedItem();
                Methods.inputVitalSigns(patient);
                populateGraphs(patient, attribute);
            } else {
                scheduledExecutorService2.shutdown();
            }

        }
    };

    ScheduledFuture scheduledTask;
    scheduledTask = scheduledExecutorService2.scheduleAtFixedRate(task, 1, 10, TimeUnit.SECONDS);

}

From source file:com.toedter.chatty.server.boot.message.web.ChatMessageRepositoryListener.java

private void notifySubscribers(ChatMessage chatMessage) {
    shouldBroadcast.set(true);/*w  w w  . java2  s  .c o  m*/
    if (!isBroadcasterInitialized.getAndSet(true)) {
        logger.info("Broadcasting initialized");
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        Runnable broadcasterRunnable = new Runnable() {
            public void run() {
                // logger.info("Broadcasting REFRESH: " + shouldBroadcast.get());
                if (shouldBroadcast.getAndSet(false)) {
                    if (broadcaster == null) {
                        ServletContext servletContext = ServletContextFactory.getDefault().getServletContext();
                        BroadcasterFactory factory = (BroadcasterFactory) servletContext
                                .getAttribute("org.atmosphere.cpr.BroadcasterFactory");
                        broadcaster = factory.lookup("/chatty/atmos/messages");
                    }
                    broadcaster.broadcast("{\"command\":\"reloadChatMessages\"}");
                }
            }
        };
        scheduledExecutorService.scheduleAtFixedRate(broadcasterRunnable, 0, 300, TimeUnit.MILLISECONDS);
    }
}

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

public ThrottleDistributedInstancesCleanupTask() {
    throttleProperties = ThrottleServiceDataHolder.getInstance().getThrottleProperties();
    cleanUpPoolSize = Integer.parseInt(throttleProperties.getThrottleDistributedCleanupPoolSize());

    noOfTimestampObjectToBeCleared = Long.parseLong(throttleProperties.getThrottleDistributedCleanupAmount());

    distributedCleanupEnabled = Boolean
            .parseBoolean(throttleProperties.getThrottleDistributedCleanupTaskEnable());

    maxNonAssociatedCounterCountToClear = Integer
            .parseInt(throttleProperties.getMaxNonAssociatedCounterCleanupAmount());

    if (log.isDebugEnabled()) {
        log.debug("Throttle window replicator pool size set to " + cleanUpPoolSize);
    }/*w  w w  .  jav a 2  s . c  om*/

    if (distributedCleanupEnabled) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(cleanUpPoolSize,
                new ThreadFactory() {

                    public Thread newThread(Runnable r) {
                        Thread t = new Thread(r);
                        t.setName("Throttle " + "Distributed Cleanup" + " Task");
                        return t;
                    }
                });

        String throttleFrequency = throttleProperties.getThrottleContextDistributedCleanupTaskFrequency();

        String distributedInstanceExpiry = throttleProperties
                .getThrottleContextDistributedExpiredInstanceTime();

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

        executor.scheduleAtFixedRate(new CleanupTask(), Integer.parseInt(throttleFrequency),
                Integer.parseInt(throttleFrequency), TimeUnit.MILLISECONDS);
        distributedInstanceExpiryMillis = Long.parseLong(distributedInstanceExpiry);
    }
}

From source file:com.alibaba.jstorm.message.netty.NettyClientAsync.java

@SuppressWarnings("rawtypes")
NettyClientAsync(Map storm_conf, ChannelFactory factory, ScheduledExecutorService scheduler, String host,
        int port, ReconnectRunnable reconnector) {
    super(storm_conf, factory, scheduler, host, port, reconnector);

    BATCH_THREASHOLD_WARN = ConfigExtension.getNettyBufferThresholdSize(storm_conf);
    blockSend = isBlockSend(storm_conf);
    directlySend = isDirectSend(storm_conf);

    flush_later = new AtomicBoolean(false);
    flushCheckInterval = Utils.getInt(storm_conf.get(Config.STORM_NETTY_FLUSH_CHECK_INTERVAL_MS), 10);

    Runnable flusher = new Runnable() {
        @Override//from www.  ja  v  a 2  s  . c o  m
        public void run() {
            flush();
        }
    };
    long initialDelay = Math.min(1000, max_sleep_ms * max_retries);
    scheduler.scheduleAtFixedRate(flusher, initialDelay, flushCheckInterval, TimeUnit.MILLISECONDS);

    clientChannelFactory = factory;

    start();
    LOG.info(this.toString());
}