Example usage for java.util.concurrent ScheduledFuture cancel

List of usage examples for java.util.concurrent ScheduledFuture cancel

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledFuture cancel.

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:Main.java

public static void main(String[] args) {
    // Get the scheduler
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    // Get a handle, starting now, with a 10 second delay
    final ScheduledFuture<?> timeHandle = scheduler.scheduleAtFixedRate(new TimePrinter(System.out), 0, 10,
            SECONDS);/*from   w  ww.j  av a2 s  . c om*/

    // Schedule the event, and run for 1 hour (60 * 60 seconds)
    scheduler.schedule(new Runnable() {
        public void run() {
            timeHandle.cancel(false);
        }
    }, 60 * 60, SECONDS);

    /**
     * On some platforms, you'll have to setup this infinite loop to see output
    while (true) { }
     */
}

From source file:com.mch.registry.ccs.server.CcsClient.java

/**
 * Sends messages to registered devices//from  ww w . ja v  a 2  s. 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.janusgraph.TestBed.java

/**
 * @param args//from   www.  j av a2s .  c  o  m
 * @throws java.io.IOException
 */
public static void main(String[] args) throws Exception {
    Method method = TestBed.class.getMethod("getInt", int.class, int.class);
    AnnotatedType rt = method.getAnnotatedReturnType();
    System.out.println(rt.getType());
    System.out.println(rt.getAnnotations().length);
    System.out.println(method.getAnnotations().length);
    for (int i = 0; i < method.getAnnotations().length; i++) {
        System.out.println(method.getAnnotations()[i]);
    }

    //        String[] s = {"a","b","c","d","e","f","g","h","i","x","u"};
    //        int len = s.length;
    //        Random random = new Random();
    //
    //        Context c = new Context(new ObserverManager(),Observer.NO_OP);
    //        //Warmup
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long before = System.nanoTime();
    //        for (int i = 0; i < 1000000000; i++) {
    //            c.observe(s[1],s[2]);
    //        }
    //        long total = System.nanoTime()-before;
    //        System.out.println("Total time: " + total/1000000);

    System.exit(0);

    final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1, new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            r.run();
        }
    });
    ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() {
        AtomicInteger atomicInt = new AtomicInteger(0);

        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    exe.submit(new Runnable() {

                        private final int number = atomicInt.incrementAndGet();

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(150);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.println(number);
                        }
                    });
                    System.out.println("Submitted: " + i);
                    //                    doSomethingExpensive(20);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 0, 1, TimeUnit.SECONDS);
    Thread.sleep(10000);
    //        future.get(1,TimeUnit.SECONDS);
    System.out.println("Cancel: " + future.cancel(false));
    System.out.println("Done: " + future.isDone());
    exe.shutdown();
    //        Thread.sleep(2000);
    System.out.println("Terminate: " + exe.awaitTermination(5, TimeUnit.SECONDS));
    System.out.println("DONE");
    NonBlockingHashMapLong<String> id1 = new NonBlockingHashMapLong<String>(128);
    ConcurrentHashMap<Long, String> id2 = new ConcurrentHashMap<Long, String>(128, 0.75f, 2);

}

From source file:org.wso2.carbon.core.deployment.RegistryBasedRepositoryUpdater.java

/**
 * Cancel a particular task which updates a repo
 *
 * @param fileSystemRepo The location in the file system
 *//*from  w w w . j a v a 2 s .  c  om*/
public static void cancelTask(String fileSystemRepo) {
    ScheduledFuture scheduledFuture = futures.get(fileSystemRepo);
    if (scheduledFuture != null) {
        scheduledFuture.cancel(true);
        exec.purge();
        futures.remove(fileSystemRepo);
    }
}

From source file:com.acmutv.ontoqa.tool.runtime.RuntimeManager.java

/**
 * Registers a periodic task./*from ww  w  .j av a  2  s .  co  m*/
 * @param task the task to execute.
 * @param delay the delay to first execution.
 * @param period the period between executions.
 * @param timeout the time to interruption.
 * @param unit the time unit.
 */
private static void registerPeriodic(Runnable task, long delay, long period, long timeout, TimeUnit unit) {
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    final ScheduledFuture<?> handler = scheduler.scheduleAtFixedRate(task, delay, period, unit);

    if (timeout > 0) {
        Runnable interrupt = () -> handler.cancel(true);
        scheduler.schedule(interrupt, timeout, TimeUnit.SECONDS);
    }
}

From source file:com.bt.aloha.util.CollectionHelper.java

public static void destroy(ConcurrentMap<String, Map<String, Object>> transients, String classname) {
    log.debug(String.format("Destroy method called on collection: %s", classname));
    for (Map<String, Object> element : transients.values()) {
        ScheduledFuture<?> future = (ScheduledFuture<?>) element.get("future");
        if (future == null || future.isCancelled() || future.isDone())
            continue;
        if (future.getDelay(TimeUnit.MILLISECONDS) > ONE_HUNDRED) {
            future.cancel(true);
            continue;
        }//  ww w. j a  va2  s. c o  m
        int counter = 0;
        while (!future.isDone() && counter++ < THREE) {
            try {
                log.debug("Waiting for future to get done for some call...");
                Thread.sleep(ONE_THOUSAND);
            } catch (InterruptedException e) {
                log.warn(e.getMessage());
                continue;
            }
        }
    }
}

From source file:be.vlaanderen.sesam.monitor.internal.MonitorServiceImpl.java

public void monitor(Collection<MonitorTask> tasks) {
    // -- cancel old
    for (ScheduledFuture future : futures) {
        future.cancel(false);
    }/*from  ww  w.  j  a v a  2  s .  com*/
    futures.clear();

    // -- schedule new --
    for (MonitorTask task : tasks) {
        log.info("Scheduling a new task: " + task.getName() + "  [" + task.getSchedule() + "]");
        if (task.isValid()) {
            futures.add(scheduler.schedule(task, new CronTrigger(task.getSchedule())));
        }
    }
}

From source file:org.xeneo.plugin.ActivityPluginRuntimeImpl.java

protected void cancelTask(String instanceid) {
    if (tasks.containsKey(instanceid)) {
        logger.info("Try to cancel task with instance id: " + instanceid);
        ScheduledFuture sf = tasks.get(instanceid);
        sf.cancel(false);
        tasks.remove(instanceid);//from  w  ww .ja va 2 s.  c o m
    }
}

From source file:com.mtt.myapp.infra.schedule.ScheduledTaskService.java

public void removeScheduledJob(Runnable runnable) {
    final ScheduledFuture scheduledTaskInfo = scheduledRunnable.remove(runnable);
    if (scheduledTaskInfo != null) {
        scheduledTaskInfo.cancel(false);
    }/*from   w  ww  .  ja  va 2  s .  c  o  m*/
}

From source file:com.bt.aloha.media.convedia.conference.ScheduledExecutorServiceMaxConferenceDurationScheduler.java

public void cancelTerminateConference(ConferenceInfo conferenceInfo) {
    log.debug(String.format("Canceling terminating scheduler for conference %s", conferenceInfo.getId()));
    ScheduledFuture<?> future = conferenceInfo.getFuture();
    if (future != null)
        log.debug(String.format("Cancel succeeded: %s", future.cancel(false)));
}