List of usage examples for java.util.concurrent ScheduledFuture get
V get() throws InterruptedException, ExecutionException;
From source file:com.twitter.heron.healthmgr.HealthManager.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); Options slaManagerCliOptions = constructCliOptions(); // parse the help options first. Options helpOptions = constructHelpOptions(); CommandLine cmd = parser.parse(helpOptions, args, true); if (cmd.hasOption("h")) { usage(slaManagerCliOptions);//from ww w . j a v a 2 s. com return; } try { cmd = parser.parse(slaManagerCliOptions, args); } catch (ParseException e) { usage(slaManagerCliOptions); throw new RuntimeException("Error parsing command line options: ", e); } HealthManagerMode mode = HealthManagerMode.cluster; if (hasOption(cmd, CliArgs.MODE)) { mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE)); } Config config; switch (mode) { case cluster: config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig()) .putAll(commandLineConfigs(cmd)).build()); break; case local: if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) { throw new IllegalArgumentException("Missing heron_home or config_path argument"); } String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME); String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH); config = Config.toLocalMode( Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null)) .putAll(commandLineConfigs(cmd)).build()); break; default: throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE)); } setupLogging(cmd, config); LOG.info("Static Heron config loaded successfully "); LOG.fine(config.toString()); // load the default config value and override with any command line values String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key()); metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName); String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key()); metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl); AbstractModule module = buildMetricsProviderModule(metricsUrl, metricSourceClassName); HealthManager healthManager = new HealthManager(config, module); LOG.info("Initializing health manager"); healthManager.initialize(); LOG.info("Starting Health Manager metirc posting thread"); HealthManagerMetrics publishingMetricsRunnable = null; if (hasOption(cmd, CliArgs.METRICSMGR_PORT)) { publishingMetricsRunnable = new HealthManagerMetrics( Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT))); } LOG.info("Starting Health Manager"); PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies); ScheduledFuture<?> future = policyExecutor.start(); if (publishingMetricsRunnable != null) { new Thread(publishingMetricsRunnable).start(); } try { future.get(); } finally { policyExecutor.destroy(); if (publishingMetricsRunnable != null) { publishingMetricsRunnable.close(); } } }
From source file:org.apache.heron.healthmgr.HealthManager.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new DefaultParser(); Options slaManagerCliOptions = constructCliOptions(); // parse the help options first. Options helpOptions = constructHelpOptions(); CommandLine cmd = parser.parse(helpOptions, args, true); if (cmd.hasOption("h")) { usage(slaManagerCliOptions);/*from w w w . ja v a 2 s . com*/ return; } try { cmd = parser.parse(slaManagerCliOptions, args); } catch (ParseException e) { usage(slaManagerCliOptions); throw new RuntimeException("Error parsing command line options: ", e); } HealthManagerMode mode = HealthManagerMode.cluster; if (hasOption(cmd, CliArgs.MODE)) { mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE)); } Config config; switch (mode) { case cluster: config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig()) .putAll(commandLineConfigs(cmd)).build()); break; case local: if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) { throw new IllegalArgumentException("Missing heron_home or config_path argument"); } String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME); String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH); config = Config.toLocalMode( Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null)) .putAll(commandLineConfigs(cmd)).build()); break; default: throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE)); } setupLogging(cmd, config); LOG.fine(Arrays.toString(cmd.getOptions())); // Add the SystemConfig into SingletonRegistry SystemConfig systemConfig = SystemConfig.newBuilder(true).putAll(Context.systemFile(config), true) .putAll(Context.overrideFile(config), true).build(); SingletonRegistry.INSTANCE.registerSingleton(SystemConfig.HERON_SYSTEM_CONFIG, systemConfig); LOG.info("Static Heron config loaded successfully "); LOG.fine(config.toString()); // load the default config value and override with any command line values String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key()); metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName); String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key()); metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl); // metrics reporting thread HealthManagerMetrics publishingMetrics = new HealthManagerMetrics( Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT))); AbstractModule module = buildBaseModule(metricsUrl, metricSourceClassName, publishingMetrics); HealthManager healthManager = new HealthManager(config, module); LOG.info("Initializing health manager"); healthManager.initialize(); LOG.info("Starting Health Manager"); PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies); ScheduledFuture<?> future = policyExecutor.start(); LOG.info("Starting Health Manager metric posting thread"); new Thread(publishingMetrics).start(); try { future.get(); } finally { policyExecutor.destroy(); publishingMetrics.close(); } }
From source file:com.mch.registry.ccs.server.CcsClient.java
/** * Sends messages to registered devices/*ww w. j a v a 2s. c o m*/ */ public static void main(String[] args) { Config config = new Config(); final String projectId = config.getProjectId(); final String key = config.getKey(); final CcsClient ccsClient = CcsClient.prepareClient(projectId, key, true); try { ccsClient.connect(); } catch (XMPPException e) { logger.log(Level.WARNING, "XMPP Exception ", e); } final Runnable sendNotifications = new Runnable() { public void run() { try { logger.log(Level.INFO, "Working Q!"); if (!isOffHours()) { //Prepare downstream message String toRegId = ""; String message = ""; String messageId = ""; Map<String, String> payload = new HashMap<String, String>(); String collapseKey = null; Long timeToLive = 10000L; Boolean delayWhileIdle = true; String messagePrefix = ""; int notificationQueueID = 0; boolean sucessfullySent = false; //Read from mysql database MySqlHandler mysql = new MySqlHandler(); ArrayList<Notification> queue = new ArrayList<Notification>(); for (int i = 1; i < 3; i++) { queue = mysql.getNotificationQueue(i); if (queue.size() > 0) { switch (i) { case 1: messagePrefix = "_V: "; break; case 2: messagePrefix = "_R: "; break; default: messagePrefix = ""; logger.log(Level.WARNING, "Unknown message type!"); } Notification notification = new Notification(); Iterator<Notification> iterator = queue.iterator(); while (iterator.hasNext()) { notification = iterator.next(); toRegId = notification.getGcmRegID(); message = notification.getNotificationText(); notificationQueueID = notification.getNotificationQueueID(); messageId = "m-" + Long.toString(random.nextLong()); payload = new HashMap<String, String>(); payload.put("message", messagePrefix + message); try { // Send the downstream message to a device. ccsClient.send(createJsonMessage(toRegId, messageId, payload, collapseKey, timeToLive, delayWhileIdle)); sucessfullySent = true; logger.log(Level.INFO, "Message sent. ID: " + notificationQueueID + ", RegID: " + toRegId + ", Text: " + message); } catch (Exception e) { mysql.prepareNotificationForTheNextDay(notificationQueueID); sucessfullySent = false; logger.log(Level.WARNING, "Message could not be sent! ID: " + notificationQueueID + ", RegID: " + toRegId + ", Text: " + message); } if (sucessfullySent) { mysql.moveNotificationToHistory(notificationQueueID); } } } else { logger.log(Level.INFO, "No notifications to send. Type: " + Integer.toString(i)); } } } } catch (Exception e) { logger.log(Level.WARNING, "Exception ", e); } } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); //Start when server starts and every 30 minutes after ScheduledFuture task = executor.scheduleAtFixedRate(sendNotifications, 0, 30, TimeUnit.MINUTES); try { task.get(); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Exception ", e); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Exception ", e); } task.cancel(false); try { executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Exception ", e); } }
From source file:org.gss_project.gss.server.ejb.TransactionHelper.java
/** * Execute the supplied command until it completes, ignoring transaction * rollbacks. Try at least TRANSACTION_RETRIES times before giving up, * each time waiting a random amount of time, using an exponential * backoff scheme. See http://en.wikipedia.org/wiki/Exponential_backoff * for the basic idea./*from w ww . jav a 2 s. c om*/ * * @param command the command to execute * @return the value returned by the command * @throws Exception any other exception thrown by the command */ public T tryExecute(final Callable<T> command) throws Exception { T returnValue = null; // Schedule a Future task to call the command after delay milliseconds. int delay = 0; ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); for (int i = 0; i < TRANSACTION_RETRIES; i++) { final int retry = i; ScheduledFuture<T> future = executor.schedule(new Callable<T>() { @Override public T call() throws Exception { return command.call(); } }, delay, TimeUnit.MILLISECONDS); try { returnValue = future.get(); break; } catch (ExecutionException e) { Throwable cause = e.getCause(); if (!(cause instanceof EJBTransactionRolledbackException) || retry == TRANSACTION_RETRIES - 1) { logger.info("Transaction retry #" + (i + 1) + " failed due to " + cause); executor.shutdownNow(); if (cause instanceof Exception) throw (Exception) cause; if (cause instanceof Error) throw (Error) cause; } delay = MIN_TIMEOUT + (int) (MIN_TIMEOUT * Math.random() * (i + 1)); String origCause = cause.getCause() == null ? cause.getClass().getName() : cause.getCause().getClass().getName(); logger.info( "Transaction retry #" + (i + 1) + " scheduled in " + delay + " msec due to " + origCause); } } executor.shutdownNow(); return returnValue; }
From source file:cherry.foundation.mail.SendMailBatchTest.java
@Test public void testMailSendException() throws Exception { final File shutdownTrigger = new File("./shutdownTrigger.txt"); shutdownTrigger.deleteOnExit();//w w w .j a v a 2 s.c o m Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() { try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) { return true; } catch (IOException ex) { return false; } } }; ScheduledExecutorService service = Executors.newScheduledThreadPool(1); ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS); SendMailBatch batch = create(1000L, shutdownTrigger, true); ExitStatus status = batch.execute(); assertEquals(ExitStatus.NORMAL, status); assertTrue(future.get().booleanValue()); assertFalse(shutdownTrigger.exists()); verify(bizDateTime, atLeastOnce()).now(); verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L)); verify(mailSendHandler, never()).sendMessage(eq(2L)); verify(mailSendHandler, never()).sendMessage(eq(3L)); }
From source file:cherry.foundation.mail.SendMailBatchTest.java
@Test public void testNormal() throws Exception { final File shutdownTrigger = new File("./shutdownTrigger.txt"); shutdownTrigger.deleteOnExit();/*from w w w.ja v a 2s.c om*/ Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() { try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) { return true; } catch (IOException ex) { return false; } } }; ScheduledExecutorService service = Executors.newScheduledThreadPool(1); ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS); SendMailBatch batch = create(1000L, shutdownTrigger, false); ExitStatus status = batch.execute(); assertEquals(ExitStatus.NORMAL, status); assertTrue(future.get().booleanValue()); assertFalse(shutdownTrigger.exists()); verify(bizDateTime, atLeastOnce()).now(); verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(2L)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L)); }
From source file:org.jas.helper.ScrobblerHelper.java
private ActionResult scrobbling(Metadata metadata) throws IOException, InterruptedException { User currentUser = controlEngine.get(Model.CURRENT_USER); if (StringUtils.isEmpty(currentUser.getUsername())) { return ActionResult.NotLogged; }/*from w ww .j a v a2 s. co m*/ if (currentUser.getSession() != null) { try { // According to Caching Rule (http://www.u-mass.de/lastfm/doc) ScheduledFuture<ActionResult> future = scheduler.schedule( new ScrobbleTask(metadata, currentUser.getSession()), REQUEST_PERIOD, TimeUnit.MICROSECONDS); return future.get(); } catch (ExecutionException eex) { log.error(eex, eex); return ActionResult.Error; } } else { log.error("There isn't a valid session"); return ActionResult.Sessionless; } }
From source file:org.apache.lens.server.session.HiveSessionService.java
@Override public void cleanupIdleSessions() throws LensException { ScheduledFuture<?> schedule = sessionExpiryThread.schedule(sessionExpiryRunnable, 0, TimeUnit.MILLISECONDS); // wait till completion try {/* www . j a v a 2 s . co m*/ schedule.get(); } catch (InterruptedException | ExecutionException e) { throw new LensException(e); } }
From source file:com.netflix.curator.framework.recipes.locks.TestReaper.java
@Test public void testSparseUseNoReap() throws Exception { final int THRESHOLD = 3000; Timing timing = new Timing(); Reaper reaper = null;//from ww w . j a v a 2 s .co m Future<Void> watcher = null; CuratorFramework client = makeClient(timing, null); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/one/two/three"); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); final Queue<Reaper.PathHolder> holders = new ConcurrentLinkedQueue<Reaper.PathHolder>(); final ExecutorService pool = Executors.newCachedThreadPool(); ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1) { @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { final Reaper.PathHolder pathHolder = (Reaper.PathHolder) command; holders.add(pathHolder); final ScheduledFuture<?> f = super.schedule(command, delay, unit); pool.submit(new Callable<Void>() { @Override public Void call() throws Exception { f.get(); holders.remove(pathHolder); return null; } }); return f; } }; reaper = new Reaper(client, service, THRESHOLD); reaper.start(); reaper.addPath("/one/two/three"); long start = System.currentTimeMillis(); boolean emptyCountIsCorrect = false; while (((System.currentTimeMillis() - start) < timing.forWaiting().milliseconds()) && !emptyCountIsCorrect) // need to loop as the Holder can go in/out of the Reaper's DelayQueue { for (Reaper.PathHolder holder : holders) { if (holder.path.endsWith("/one/two/three")) { emptyCountIsCorrect = (holder.emptyCount > 0); break; } } Thread.sleep(1); } Assert.assertTrue(emptyCountIsCorrect); client.create().forPath("/one/two/three/foo"); Thread.sleep(2 * (THRESHOLD / Reaper.EMPTY_COUNT_THRESHOLD)); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); client.delete().forPath("/one/two/three/foo"); Thread.sleep(THRESHOLD); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { if (watcher != null) { watcher.cancel(true); } IOUtils.closeQuietly(reaper); IOUtils.closeQuietly(client); } }
From source file:cherry.foundation.mail.SendMailBatchTest.java
@Test public void testInterrupt() throws Exception { final File shutdownTrigger = new File("./shutdownTrigger.txt"); shutdownTrigger.deleteOnExit();/*from w w w . j a v a2 s .c om*/ Callable<Boolean> callable = new Callable<Boolean>() { @Override public Boolean call() { try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) { return true; } catch (IOException ex) { return false; } } }; ScheduledExecutorService service = Executors.newScheduledThreadPool(1); ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS); final Thread currentThread = Thread.currentThread(); ScheduledFuture<Boolean> interrupt = service.schedule(new Callable<Boolean>() { @Override public Boolean call() { currentThread.interrupt(); return true; } }, 2L, TimeUnit.SECONDS); SendMailBatch batch = create(1000L, shutdownTrigger, false); ExitStatus status = batch.execute(); assertEquals(ExitStatus.NORMAL, status); assertTrue(future.get().booleanValue()); assertTrue(interrupt.get().booleanValue()); assertFalse(shutdownTrigger.exists()); verify(bizDateTime, atLeastOnce()).now(); verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(2L)); verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L)); }