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:github.daneren2005.dsub.fragments.NowPlayingFragment.java

private void onResumeHandlers() {
    final Handler handler = new Handler();
    executorService = Executors.newSingleThreadScheduledExecutor();
    setControlsVisible(true);/*from   www  .j  a v a2s.c om*/

    final DownloadService downloadService = getDownloadService();
    if (downloadService == null || downloadService.getCurrentPlaying() == null || startFlipped) {
        playlistFlipper.setDisplayedChild(1);
    }
    if (downloadService != null && downloadService.getKeepScreenOn()) {
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    } else {
        context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    updateButtons();

    if (currentPlaying == null && downloadService != null
            && currentPlaying == downloadService.getCurrentPlaying()) {
        getImageLoader().loadImage(albumArtImageView, (Entry) null, true, false);
    }

    context.runWhenServiceAvailable(new Runnable() {
        @Override
        public void run() {
            if (primaryFragment) {
                DownloadService downloadService = getDownloadService();
                downloadService.startRemoteScan();
                downloadService.addOnSongChangedListener(NowPlayingFragment.this, true);
            }
            updateRepeatButton();
        }
    });
}

From source file:com.networknt.client.oauth.OauthHelper.java

/**
 * renew the given Jwt jwt asynchronously.
 * When fail, it will swallow the exception, so no need return type to be handled by caller.
 * @param jwt the jwt you want to renew/*w  ww.j  ava2  s  .c  om*/
 */
private static void renewCCTokenAsync(final Jwt jwt) {
    // Not expired yet, try to renew async but let requests use the old token.
    logger.trace("In renew window but token is not expired yet.");
    if (!jwt.isRenewing() || System.currentTimeMillis() > jwt.getEarlyRetryTimeout()) {
        jwt.setRenewing(true);
        jwt.setEarlyRetryTimeout(System.currentTimeMillis() + jwt.getEarlyRefreshRetryDelay());
        logger.trace("Retrieve token async is called while token is not expired yet");

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        executor.schedule(() -> {
            Result<Jwt> result = getCCTokenRemotely(jwt);
            if (result.isFailure()) {
                // swallow the exception here as it is on a best effort basis.
                logger.error("Async retrieve token error with status: {}", result.getError().toString());
            }
            //set renewing flag to false after response, doesn't matter if it's success or fail.
            jwt.setRenewing(false);
        }, 50, TimeUnit.MILLISECONDS);
        executor.shutdown();
    }
}

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

public static void main(String[] args) {
    try {//from  ww w  . j  av a2 s . c o m
        CommandLine cl = parseComandLine(args);
        final UnvSCP main = new UnvSCP(!cl.hasOption("dicomdir"));
        CLIUtils.configure(main.fsInfo, cl);
        CLIUtils.configureBindServer(main.conn, main.ae, cl);
        CLIUtils.configure(main.conn, cl);
        configureDicomFileSet(main, cl);
        configureLog(main, cl);
        configureAsyncMode(main, cl);
        configureManualUploading(main, cl);
        configureCompression(main, cl);
        configurePushMethod(main, cl);
        configureTransferCapability(main, cl);
        configureRoleSelectionsAndExtendedNegotiations(main, cl);
        configureInstanceAvailability(main, cl);
        configureStgCmt(main, cl);
        configureSendPending(main, cl);
        configureDestinationOverride(main, cl);
        configureSession(main, cl);
        configureRemoteConnections(main, cl);
        configureVisualInterface(main, cl);
        ExecutorService executorService = Executors.newCachedThreadPool();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        main.device.setScheduledExecutor(scheduledExecutorService);
        main.device.setExecutor(executorService);
        main.device.bindConnections();

        main.device.setAssociationHandler(new AssociationHandler() {
            @Override
            protected AAssociateAC negotiate(Association as, AAssociateRQ rq) throws IOException {
                //as.getCallingAET(); as.getRemoteAET(); // show the same result

                LOG.info("{} >> A-ASSOCIATE-RQ {}",
                        "Association" + as.toString().replaceFirst("\\b[^+^-]*", ""),
                        (rq != null ? rq.getCallingAET() : ""));

                try {
                    UnvWebClient webClient = new UnvWebClient(main.dicomUrl.toString());
                    webClient.addListener(main, new DicomClientMetaInfo(as));
                    webClient.setBasicParams(main.emsowUsername, main.emsowPassword, "EMSOW-AUTH", as);

                    if (main.notConcurrent) {
                        synchronized (main) {
                            webClient.sendPostRequest();
                        }
                    } else {
                        webClient.sendPostRequest();
                    }

                    CAuthWebResponse cawr = webClient.parseJsonResponse(CAuthWebResponse.class);
                    Collection<CAuthWebResponse.AERecord> ae_client_list = cawr.getClientsData();
                    if (ae_client_list != null) {
                        synchronized (main.emsowClientAets) {
                            main.emsowServerAeMeta = cawr.getServerData();
                            main.emsowClientAets.clear();
                            for (CAuthWebResponse.AERecord aerec : ae_client_list) {
                                main.emsowClientAets.put(aerec.getAET(), aerec);
                            }
                            main.isPullForUnknownEnabled = cawr.isPullForUnknownEnabled();
                            main.isPushForUnknownEnabled = cawr.isPushForUnknownEnabled();
                        }
                        if (UnvSCP.isDynamicAEList) {
                            synchronized (main.remoteConnections) {
                                main.remoteConnections.clear();
                                for (CAuthWebResponse.AERecord aerec : ae_client_list) {
                                    String host = (aerec.getHost() == null) ? "" : aerec.getHost();
                                    String port = (aerec.getHost() == null || "".equals(aerec.getPort().trim()))
                                            ? "104"
                                            : aerec.getPort();
                                    main.addRemoteConnection(aerec.getAET(),
                                            UnvSCP.createAllowedConnection(host + ":" + port));
                                }
                            }
                        }
                    }
                } catch (IOException ioe) {
                    throw new UnvAAssociateRJ(UnvAAssociateRJ.RESULT_REJECTED_PERMANENT,
                            UnvAAssociateRJ.SOURCE_SERVICE_USER,
                            UnvAAssociateRJ.REASON_CALLING_AET_NOT_RECOGNIZED, ioe.getMessage());
                } catch (Exception e) {
                    throw new UnvAAssociateRJ(UnvAAssociateRJ.RESULT_REJECTED_PERMANENT,
                            UnvAAssociateRJ.SOURCE_SERVICE_USER, UnvAAssociateRJ.REASON_USER_DEFINED,
                            e.getMessage());
                }

                AAssociateAC ac = super.negotiate(as, rq);
                for (RoleSelection rs : main.roleSelections) {
                    ac.addRoleSelection(rs);
                }
                for (ExtendedNegotiation extNeg : main.extendedNegotiaions) {
                    ac.addExtendedNegotiation(extNeg);
                }
                return ac;
            }
        });

        if (main.async) {
            AsyncSenderTask asyncSenderTask = new AsyncSenderTask(main.dicomUrl, main.emsowUsername,
                    main.emsowPassword, main.storageDir, main.tmpDir, main.badFilesDir, main.sleepTime,
                    main.notConcurrent, main.compressionLevel, main);
            asyncSenderTask.addSenderTaskListener(main.activityWindow);
            main.asyncSender = new Thread(asyncSenderTask, "ASYNC");
            main.asyncSender.setDaemon(true);
            main.asyncSender.start();
        }

        if (main.uplDir != null && main.uplBadFilesDir != null) {
            Properties params = UnvWebClient.getUploadParams(main.ae, main.conn);
            DcmFileSenderTask dcmFileSenderTask = new DcmFileSenderTask(main.dicomUrl, main.emsowUsername,
                    main.emsowPassword, main.uplDir, main.tmpDir, main.uplBadFilesDir, main.uplSleepTime,
                    main.notConcurrent, main.compressionLevel, main, params);
            dcmFileSenderTask.addSenderTaskListener(main.activityWindow);
            main.dcmFileSender = new Thread(dcmFileSenderTask, "UPL");
            main.dcmFileSender.setDaemon(true);
            main.dcmFileSender.start();
        }
    } catch (ParseException e) {
        System.err.println("unvscp: " + e.getMessage());
        System.err.println(rb.getString("try"));
        System.exit(2);
    } catch (Exception e) {
        System.err.println("unvscp: " + e.getMessage());
        e.printStackTrace();
        System.exit(2);
    }
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

@SuppressWarnings("unchecked")
@Test //INT-3722/*from  ww w  .  ja v  a  2  s.  co  m*/
public void testGatewayRelease() throws Exception {
    TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0);
    in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    final TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(in);
    final AtomicInteger count = new AtomicInteger(2);
    in.registerListener(message -> {
        if (!(message instanceof ErrorMessage)) {
            if (count.decrementAndGet() < 1) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            handler.handleMessage(message);
        }
        return false;
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    TestingUtilities.waitListening(in, null);
    int port = in.getPort();
    TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port);
    out.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 2);
    final TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(cache);
    QueueChannel outputChannel = new QueueChannel();
    gate.setOutputChannel(outputChannel);
    gate.setBeanFactory(mock(BeanFactory.class));
    gate.afterPropertiesSet();
    Log logger = spy(TestUtils.getPropertyValue(gate, "logger", Log.class));
    new DirectFieldAccessor(gate).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(new Answer<Void>() {

        private final CountDownLatch latch = new CountDownLatch(2);

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            String log = invocation.getArgument(0);
            if (log.startsWith("Response")) {
                Executors.newSingleThreadScheduledExecutor()
                        .execute(() -> gate.handleMessage(new GenericMessage<>("bar")));
                // hold up the first thread until the second has added its pending reply
                latch.await(10, TimeUnit.SECONDS);
            } else if (log.startsWith("Added")) {
                latch.countDown();
            }
            return null;
        }
    }).when(logger).debug(anyString());
    gate.start();
    gate.handleMessage(new GenericMessage<String>("foo"));
    Message<byte[]> result = (Message<byte[]>) outputChannel.receive(10000);
    assertNotNull(result);
    assertEquals("foo", new String(result.getPayload()));
    result = (Message<byte[]>) outputChannel.receive(10000);
    assertNotNull(result);
    assertEquals("bar", new String(result.getPayload()));
    handler.stop();
    gate.stop();
    verify(logger, never()).error(anyString());
}

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 a2s  .co  m
    }, timer, timer, TimeUnit.SECONDS);

}

From source file:org.usergrid.persistence.cassandra.CassandraService.java

public void startClusterHealthCheck() {

    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleWithFixedDelay(new Runnable() {
        @Override//from ww  w .j ava2  s  .  c  om
        public void run() {
            if (cluster != null) {
                HConnectionManager connectionManager = cluster.getConnectionManager();
                if (connectionManager != null) {
                    clusterUp = !connectionManager.getHosts().isEmpty();
                }
            }
        }
    }, 1, 5, TimeUnit.SECONDS);

}

From source file:com.leanplum.Leanplum.java

/**
 * Send a heartbeat every 15 minutes while the app is running.
 *///w ww . j a va  2s  .  c  o m
private static void startHeartbeat() {
    synchronized (heartbeatLock) {
        heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
        heartbeatExecutor.scheduleAtFixedRate(new Runnable() {
            public void run() {
                try {
                    Request.post(Constants.Methods.HEARTBEAT, null).sendIfDelayed();
                } catch (Throwable t) {
                    Util.handleException(t);
                }
            }
        }, 15, 15, TimeUnit.MINUTES);
    }
}

From source file:org.broeuschmeul.android.gps.usb.provider.driver.USBGpsManager.java

/**
 * Enables the USB GPS Provider./*from  w  w w .  j av a  2 s  . c o m*/
 *
 * @return
 */
public synchronized boolean enable() {
    IntentFilter permissionFilter = new IntentFilter(ACTION_USB_PERMISSION);
    permissionFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    notificationManager.cancel(R.string.service_closed_because_connection_problem_notification_title);

    if (!enabled) {
        log("enabling USB GPS manager");

        if (!isMockLocationEnabled()) {
            if (BuildConfig.DEBUG || debug)
                Log.e(LOG_TAG, "Mock location provider OFF");
            disable(R.string.msg_mock_location_disabled);
            return this.enabled;

        } else if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(callingService,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            if (BuildConfig.DEBUG || debug)
                Log.e(LOG_TAG, "No location permission given");
            disable(R.string.msg_no_location_permission);
            return this.enabled;

        } else {
            gpsDev = getDeviceFromAttached();

            // This thread will be run by the executor at a delay of 1 second, and will be
            // run again if the read thread dies. It will run until maximum number of retries
            // is exceeded
            Runnable connectThread = new Runnable() {
                @Override
                public void run() {
                    try {
                        debugLog("Starting connect thread");
                        connected = false;
                        gpsDev = getDeviceFromAttached();

                        if (nbRetriesRemaining > 0) {
                            if (connectedGps != null) {
                                connectedGps.close();
                            }

                            if (gpsDev != null) {
                                debugLog("GPS device: " + gpsDev.getDeviceName());

                                PendingIntent permissionIntent = PendingIntent.getBroadcast(callingService, 0,
                                        new Intent(ACTION_USB_PERMISSION), 0);
                                UsbDevice device = gpsDev;

                                if (device != null && usbManager.hasPermission(device)) {
                                    debugLog("We have permission, good!");
                                    openConnection(device);

                                } else if (device != null) {
                                    debugLog("We don't have permission, so requesting...");
                                    usbManager.requestPermission(device, permissionIntent);

                                } else {
                                    if (BuildConfig.DEBUG || debug)
                                        Log.e(LOG_TAG, "Error while establishing connection: no device - "
                                                + gpsVendorId + ": " + gpsProductId);
                                    disable(R.string.msg_usb_provider_device_not_connected);
                                }
                            } else {
                                if (BuildConfig.DEBUG || debug)
                                    Log.e(LOG_TAG, "Device not connected");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        nbRetriesRemaining--;
                        if (!connected) {
                            disableIfNeeded();
                        }
                    }

                }
            };

            if (gpsDev != null) {
                this.enabled = true;
                callingService.registerReceiver(permissionAndDetachReceiver, permissionFilter);

                debugLog("USB GPS manager enabled");

                notificationPool = Executors.newSingleThreadExecutor();
                debugLog("starting connection and reading thread");
                connectionAndReadingPool = Executors.newSingleThreadScheduledExecutor();

                debugLog("starting connection to socket task");
                connectionAndReadingPool.scheduleWithFixedDelay(connectThread, 1000, 1000,
                        TimeUnit.MILLISECONDS);

                if (sirfGps) {
                    enableSirfConfig(sharedPreferences);
                }
            }
        }

        if (!this.enabled) {
            if (BuildConfig.DEBUG || debug)
                Log.e(LOG_TAG, "Error while establishing connection: no device");
            disable(R.string.msg_usb_provider_device_not_connected);
        }
    }
    return this.enabled;
}

From source file:tv.phantombot.PhantomBot.java

public void doRefreshGameWispToken() {

    long curTime = System.currentTimeMillis() / 1000L;

    if (!dataStore.exists("settings", "gameWispRefreshTime")) {
        dataStore.set("settings", "gameWispRefreshTime", String.valueOf(curTime));
    }/*  w ww  . j a va  2s  .com*/

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(() -> {
        Thread.currentThread().setName("tv.phantombot.PhantomBot::doRefreshGameWispToken");

        long curTime1 = System.currentTimeMillis() / 1000L;
        String lastRunStr = dataStore.GetString("settings", "", "gameWispRefreshTime");
        long lastRun = Long.parseLong(lastRunStr);
        if ((curTime1 - lastRun) > (10 * 24 * 60 * 60)) {
            // 10 days, token expires every 35.
            dataStore.set("settings", "gameWispRefreshTime", String.valueOf(curTime1));
            updateGameWispTokens(GameWispAPIv1.instance().refreshToken());
        }
    }, 0, 1, TimeUnit.DAYS);
}