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:com.xiaoya.framepager.SuperAwesomeCardFragment.java

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    if (position == 0) {
        timeTask = new ViewpagerTask();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 105//from  www  . j  av  a 2s .  c o  m
        scheduledExecutorService.scheduleAtFixedRate(timeTask, 5, 3, TimeUnit.SECONDS);
    }
}

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 {/*from  w ww  . j  a  va  2  s . c om*/
        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:io.fabric8.kubernetes.client.dsl.internal.RollingUpdater.java

/**
 * Lets wait until there are enough Ready pods of the given RC
 *//*from w ww  . ja  v a2s .c om*/
private void waitUntilPodsAreReady(final T obj, final String namespace, final int requiredPodCount) {
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    final AtomicInteger podCount = new AtomicInteger(0);

    final Runnable readyPodsPoller = new Runnable() {
        public void run() {
            PodList podList = listSelectedPods(obj);
            int count = 0;
            List<Pod> items = podList.getItems();
            for (Pod item : items) {
                for (PodCondition c : item.getStatus().getConditions()) {
                    if (c.getType().equals("Ready") && c.getStatus().equals("True")) {
                        count++;
                    }
                }
            }
            podCount.set(count);
            if (count == requiredPodCount) {
                countDownLatch.countDown();
            }
        }
    };

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture poller = executor.scheduleWithFixedDelay(readyPodsPoller, 0, 1, TimeUnit.SECONDS);
    ScheduledFuture logger = executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            LOG.debug("Only {}/{} pod(s) ready for {}: {} in namespace: {} seconds so waiting...",
                    podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace);
        }
    }, 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
    try {
        countDownLatch.await(rollingTimeoutMillis, TimeUnit.MILLISECONDS);
        executor.shutdown();
    } catch (InterruptedException e) {
        poller.cancel(true);
        logger.cancel(true);
        executor.shutdown();
        LOG.warn(
                "Only {}/{} pod(s) ready for {}: {} in namespace: {}  after waiting for {} seconds so giving up",
                podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace,
                TimeUnit.MILLISECONDS.toSeconds(rollingTimeoutMillis));
    }
}

From source file:org.apache.hadoop.hbase.test.IntegrationTestTimeBoundedRequestsWithRegionReplicas.java

@Override
protected void runIngestTest(long defaultRunTime, long keysPerServerPerIter, int colsPerKey, int recordSize,
        int writeThreads, int readThreads) throws Exception {
    LOG.info("Cluster size:" + util.getHBaseClusterInterface().getClusterStatus().getServersSize());

    long start = System.currentTimeMillis();
    String runtimeKey = String.format(RUN_TIME_KEY, this.getClass().getSimpleName());
    long runtime = util.getConfiguration().getLong(runtimeKey, defaultRunTime);
    long startKey = 0;

    long numKeys = getNumKeys(keysPerServerPerIter);

    // write data once
    LOG.info("Writing some data to the table");
    writeData(colsPerKey, recordSize, writeThreads, startKey, numKeys);

    // flush the table
    LOG.info("Flushing the table");
    Admin admin = util.getHBaseAdmin();//from   w  w w.  j a  v  a2s.  c  o  m
    admin.flush(getTablename());

    // re-open the regions to make sure that the replicas are up to date
    long refreshTime = conf.getLong(StorefileRefresherChore.REGIONSERVER_STOREFILE_REFRESH_PERIOD, 0);
    if (refreshTime > 0 && refreshTime <= 10000) {
        LOG.info("Sleeping " + refreshTime + "ms to ensure that the data is replicated");
        Threads.sleep(refreshTime * 3);
    } else {
        LOG.info("Reopening the table");
        admin.disableTable(getTablename());
        admin.enableTable(getTablename());
    }

    // We should only start the ChaosMonkey after the readers are started and have cached
    // all of the region locations. Because the meta is not replicated, the timebounded reads
    // will timeout if meta server is killed.
    // We will start the chaos monkey after 1 minute, and since the readers are reading random
    // keys, it should be enough to cache every region entry.
    long chaosMonkeyDelay = conf.getLong(String.format("%s.%s", TEST_NAME, CHAOS_MONKEY_DELAY_KEY),
            DEFAUL_CHAOS_MONKEY_DELAY);
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    LOG.info(String.format("ChaosMonkey delay is : %d seconds. Will start %s " + "ChaosMonkey after delay",
            chaosMonkeyDelay / 1000, monkeyToUse));
    ScheduledFuture<?> result = executorService.schedule(new Runnable() {
        @Override
        public void run() {
            try {
                LOG.info("Starting ChaosMonkey");
                monkey.start();
                monkey.waitForStop();
            } catch (Exception e) {
                LOG.warn(StringUtils.stringifyException(e));
            }

        }
    }, chaosMonkeyDelay, TimeUnit.MILLISECONDS);

    // set the intended run time for the reader. The reader will do read requests
    // to random keys for this amount of time.
    long remainingTime = runtime - (System.currentTimeMillis() - start);
    LOG.info("Reading random keys from the table for " + remainingTime / 60000 + " min");
    this.conf.setLong(String.format(RUN_TIME_KEY, TimeBoundedMultiThreadedReader.class.getSimpleName()),
            remainingTime); // load tool shares the same conf

    // now start the readers which will run for configured run time
    try {
        int ret = loadTool
                .run(getArgsForLoadTestTool("-read", String.format("100:%d", readThreads), startKey, numKeys));
        if (0 != ret) {
            String errorMsg = "Verification failed with error code " + ret;
            LOG.error(errorMsg);
            Assert.fail(errorMsg);
        }
    } finally {
        if (result != null)
            result.cancel(false);
        monkey.stop("Stopping the test");
        monkey.waitForStop();
        executorService.shutdown();
    }
}

From source file:com.ah.be.license.AeroLicenseTimer.java

/**
 * Change the permanent entitle key can manage HiveAP number
 *///  ww  w  . j  av  a 2s . com
public void permanentEntitleKeyTimer() {
    PermanentEntitleKeyTask taskEvalue = new PermanentEntitleKeyTask();
    if (null == permanentTimer || permanentTimer.isShutdown()) {
        permanentTimer = Executors.newSingleThreadScheduledExecutor();
        permanentFuture = permanentTimer.scheduleWithFixedDelay(taskEvalue, 5, 6 * 60, TimeUnit.MINUTES);
        //permanentFuture = permanentTimer.scheduleAtFixedRate(taskEvalue, 5, 5, TimeUnit.MINUTES);

        BeLogTools.info(HmLogConst.M_TRACER | HmLogConst.M_LICENSE,
                "<BE Thread> Permanent Entitle Key timer is running...");
    }
}

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * ?DiamondSubscriber<br>//from  w ww. j  a  v a 2  s .  c  o  m
 * 1.?DataId??<br>
 * 2.??DataId??<br>
 */
public synchronized void start() {
    if (isRun) {
        return;
    }

    if (null == scheduledExecutor || scheduledExecutor.isTerminated()) {
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    }

    localConfigInfoProcessor.start(this.diamondConfigure.getFilePath() + "/" + DATA_DIR);
    serverAddressProcessor = new ServerAddressProcessor(this.diamondConfigure, this.scheduledExecutor);
    serverAddressProcessor.setClusterType(clusterType);
    serverAddressProcessor.start();

    this.snapshotConfigInfoProcessor = new SnapshotConfigInfoProcessor(
            this.diamondConfigure.getFilePath() + "/" + SNAPSHOT_DIR);
    // domainNamePos
    randomDomainNamePos();

    initHttpClient();

    // ?
    isRun = true;

    if (log.isInfoEnabled()) {
        log.info("???" + this.diamondConfigure.getDomainNameList());
    }

    if (MockServer.isTestMode()) {
        bFirstCheck = false;
    } else {
        // 
        this.diamondConfigure.setPollingIntervalTime(Constants.POLLING_INTERVAL_TIME);
    }
    // 
    rotateCheckConfigInfo();

    addShutdownHook();
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)}
 * ??????/*from  w  w  w .j  a va 2  s  .  c om*/
 * 
 * <p>
 * ?????????????????????
 * </p>
 */
public void newSingleThreadScheduledExecutorAtFixedRateTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new ExecutorRunnable("A", 1), 1, 2, TimeUnit.SECONDS);
    shutdown(executorService);
}

From source file:fr.bmartel.fadecandy.FadecandySingleton.java

/**
 * Build the singleton.//from w  w  w. j a  v a 2  s .c  o  m
 *
 * @param context
 */
public FadecandySingleton(Context context) {

    prefs = context.getSharedPreferences(Constants.PREFERENCE_PREFS, Context.MODE_PRIVATE);
    mLedCount = prefs.getInt(AppConstants.PREFERENCE_FIELD_LEDCOUNT, AppConstants.DEFAULT_LED_COUNT);
    mServerMode = prefs.getBoolean(AppConstants.PREFERENCE_FIELD_SERVER_MODE, AppConstants.DEFAULT_SERVER_MODE);
    mRemoteServerIp = prefs.getString(AppConstants.PREFERENCE_FIELD_REMOTE_SERVER_IP,
            AppConstants.DEFAULT_SERVER_IP);
    mRemoteServerPort = prefs.getInt(AppConstants.PREFERENCE_FIELD_REMOTE_SERVER_PORT,
            AppConstants.DEFAULT_SERVER_PORT);
    mSparkSpan = prefs.getInt(AppConstants.PREFERENCE_FIELD_SPARK_SPAN, AppConstants.DEFAULT_SPARK_SPAN);
    mSparkSpeed = prefs.getInt(AppConstants.PREFERENCE_FIELD_SPARK_SPEED, AppConstants.DEFAULT_SPARK_SPEED);
    mMixerDelay = prefs.getInt(AppConstants.PREFERENCE_FIELD_MIXER_DELAY, AppConstants.DEFAULT_MIXER_DELAY);
    mPulseDelay = prefs.getInt(AppConstants.PREFERENCE_FIELD_PULSE_DELAY, AppConstants.DEFAULT_PULSE_DELAY);
    mPulsePause = prefs.getInt(AppConstants.PREFERENCE_FIELD_PULSE_PAUSE, AppConstants.DEFAULT_PULSE_PAUSE);
    mTemperature = prefs.getInt(AppConstants.PREFERENCE_FIELD_TEMPERATURE, AppConstants.DEFAULT_TEMPERATURE);
    mCurrentBrightness = prefs.getInt(AppConstants.PREFERENCE_FIELD_BRIGHTNESS,
            AppConstants.DEFAULT_BRIGHTNESS);
    mColor = prefs.getInt(AppConstants.PREFERENCE_FIELD_COLOR, AppConstants.DEFAULT_COLOR);

    mExecutorService = Executors.newSingleThreadScheduledExecutor();

    mContext = context;

    mIsBrightnessUpdate = false;
    mIsSpanUpdate = false;

    //build Fadecandy client to bind Fadecandy service & start server

    mFadecandyClient = new FadecandyClient(mContext, new IFcServerEventListener() {

        @Override
        public void onServerStart() {

            Log.v(TAG, "onServerStart");

            for (int i = 0; i < mListeners.size(); i++) {
                mListeners.get(i).onServerStart();
            }

            initOpcClient();
        }

        @Override
        public void onServerClose() {

            Log.v(TAG, "onServerClose");

            for (int i = 0; i < mListeners.size(); i++) {
                mListeners.get(i).onServerClose();
            }
        }

        @Override
        public void onServerError(ServerError error) {

        }

    }, new IUsbEventListener() {
        @Override
        public void onUsbDeviceAttached(UsbItem usbItem) {
            for (int i = 0; i < mListeners.size(); i++) {
                mListeners.get(i).onUsbDeviceAttached(usbItem);
            }
        }

        @Override
        public void onUsbDeviceDetached(UsbItem usbItem) {
            for (int i = 0; i < mListeners.size(); i++) {
                mListeners.get(i).onUsbDeviceDetached(usbItem);
            }
        }
    }, "fr.bmartel.fadecandy/.activity.MainActivity");

    if (mServerMode) {
        mFadecandyClient.startServer();
    } else {
        createWebsocketClient();
    }

    initOpcClient();
}

From source file:org.hyperic.hq.measurement.agent.server.ScheduleThread.java

ScheduleThread(Sender sender, MeasurementValueGetter manager, Properties config) throws AgentStartException {
    this.statsCollector = AgentStatsCollector.getInstance();
    this.statsCollector.register(SCHEDULE_THREAD_METRIC_COLLECT_FAILED);
    this.statsCollector.register(SCHEDULE_THREAD_METRIC_TASKS_SUBMITTED);
    this.statsCollector.register(SCHEDULE_THREAD_METRICS_COLLECTED_TIME);
    this.agentConfig = config;
    this.manager = manager;
    this.sender = sender;
    int tmp = getFudgeFactor();
    if (tmp <= 0) {
        offset = ONE_SECOND;/*  w ww  . ja va  2 s.co  m*/
    } else {
        offset = tmp;
        log.info("fudgeFactor is set to " + offset + " ms");
    }

    String sLogFetchTimeout = agentConfig.getProperty(PROP_FETCH_LOG_TIMEOUT);
    if (sLogFetchTimeout != null) {
        try {
            logFetchTimeout = Integer.parseInt(sLogFetchTimeout);
            log.info("Log fetch timeout set to " + logFetchTimeout);
        } catch (NumberFormatException exc) {
            log.error("Invalid setting for " + PROP_FETCH_LOG_TIMEOUT + " value=" + sLogFetchTimeout
                    + ", using defaults.");
        }
    }

    String sCancelTimeout = agentConfig.getProperty(PROP_CANCEL_TIMEOUT);
    if (sCancelTimeout != null) {
        try {
            cancelTimeout = Integer.parseInt(sCancelTimeout);
            log.info("Cancel timeout set to " + cancelTimeout);
        } catch (NumberFormatException exc) {
            log.error("Invalid setting for " + PROP_CANCEL_TIMEOUT + " value=" + sCancelTimeout
                    + ", using defaults.");
        }
    }

    metricVerificationService = Executors.newSingleThreadScheduledExecutor();
    metricVerificationTask = metricVerificationService.scheduleAtFixedRate(new MetricVerificationTask(),
            POLL_PERIOD, POLL_PERIOD, TimeUnit.MILLISECONDS);
    metricLoggingTask = metricVerificationService.scheduleAtFixedRate(new MetricLoggingTask(), 1, 600,
            TimeUnit.SECONDS);
    AgentDiagnostics.getInstance().addDiagnostic(this);

    // by default we the deduction feature is on
    Boolean deductServerOffset = PropertiesUtil
            .getBooleanValue(agentConfig.getProperty(ServerTimeDiff.PROP_DEDUCT_SERVER_TIME_DIFF), true);

    deductServerTimeDiff = deductServerOffset;
}

From source file:org.apache.nifi.websocket.jetty.JettyWebSocketClient.java

@OnEnabled
@Override/*from   ww  w  .j  a  va  2 s .  c o m*/
public void startClient(final ConfigurationContext context) throws Exception {

    final SSLContextService sslService = context.getProperty(SSL_CONTEXT)
            .asControllerService(SSLContextService.class);
    SslContextFactory sslContextFactory = null;
    if (sslService != null) {
        sslContextFactory = createSslFactory(sslService, false, false);
    }
    client = new WebSocketClient(sslContextFactory);

    configurePolicy(context, client.getPolicy());
    final String userName = context.getProperty(USER_NAME).evaluateAttributeExpressions().getValue();
    final String userPassword = context.getProperty(USER_PASSWORD).evaluateAttributeExpressions().getValue();
    if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPassword)) {
        final String charsetName = context.getProperty(AUTH_CHARSET).evaluateAttributeExpressions().getValue();
        if (StringUtils.isEmpty(charsetName)) {
            throw new IllegalArgumentException(AUTH_CHARSET.getDisplayName() + " was not specified.");
        }
        final Charset charset = Charset.forName(charsetName);
        final String base64String = Base64
                .encodeBase64String((userName + ":" + userPassword).getBytes(charset));
        authorizationHeader = "Basic " + base64String;
    } else {
        authorizationHeader = null;
    }

    client.start();
    activeSessions.clear();

    webSocketUri = new URI(context.getProperty(WS_URI).evaluateAttributeExpressions().getValue());
    connectionTimeoutMillis = context.getProperty(CONNECTION_TIMEOUT).evaluateAttributeExpressions()
            .asTimePeriod(TimeUnit.MILLISECONDS);

    final Long sessionMaintenanceInterval = context.getProperty(SESSION_MAINTENANCE_INTERVAL)
            .evaluateAttributeExpressions().asTimePeriod(TimeUnit.MILLISECONDS);

    sessionMaintenanceScheduler = Executors.newSingleThreadScheduledExecutor();
    sessionMaintenanceScheduler.scheduleAtFixedRate(() -> {
        try {
            maintainSessions();
        } catch (final Exception e) {
            getLogger().warn("Failed to maintain sessions due to {}", new Object[] { e }, e);
        }
    }, sessionMaintenanceInterval, sessionMaintenanceInterval, TimeUnit.MILLISECONDS);
}