List of usage examples for java.util Timer cancel
public void cancel()
From source file:MyTimerTask.java
public static void main(String[] args) { // creating timer task, timer TimerTask tasknew = new MyTimerTask(); Timer timer = new Timer(); // scheduling the task timer.scheduleAtFixedRate(tasknew, new Date(), 10); // cancel task timer.cancel(); // purging the timer System.out.println("purge value :" + timer.purge()); }
From source file:MainClass.java
public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new DisplayQuestionTask(), 0, 10 * 1000); try {//w w w. j a va 2 s . c o m Thread.sleep(10000); } catch (InterruptedException e) { } timer.cancel(); }
From source file:AutoTask.java
public static void main(String args[]) { AutoTask myTask = new AutoTask(); Timer bkTimer = new Timer(); bkTimer.schedule(myTask, 2000, 2000); for (int i = 0; i < 5; i++) { try {// w w w . j a va 2 s . co m Thread.sleep(2100); } catch (InterruptedException exc) { } } bkTimer.cancel(); }
From source file:MyTimerTask.java
public static void main(String args[]) { MyTimerTask myTask = new MyTimerTask(); Timer myTimer = new Timer(); /*//from ww w. j a va2 s . c o m * Set an initial delay of 1 second, then repeat every half second. */ myTimer.schedule(myTask, 1000, 500); try { Thread.sleep(5000); } catch (InterruptedException exc) { } myTimer.cancel(); }
From source file:hydrograph.server.execution.tracking.client.main.HydrographMain.java
/** * The main method.//from w w w . j a va 2 s. c om * * @param args * the arguments * @throws Exception * the exception */ public static void main(String[] args) throws Exception { HydrographMain hydrographMain = new HydrographMain(); final Timer timer = new Timer(); final CountDownLatch latch = new CountDownLatch(1); try { Session session = null; boolean isExecutionTracking = false; String[] argsList = args; List<String> argumentList = new ArrayList<String>(Arrays.asList(args)); final String jobId = hydrographMain.getJobId(argumentList); getLogLevel(argumentList).ifPresent(x -> { if (!x.equalsIgnoreCase(String.valueOf(logger.getLevel()))) { setLoglevel(x); } else { Optional.empty(); } }); logger.info("Argument List: " + argumentList.toString()); String trackingClientSocketPort = hydrographMain.getTrackingClientSocketPort(argumentList); if (argumentList.contains(Constants.IS_TRACKING_ENABLE)) { int index = argumentList.indexOf(Constants.IS_TRACKING_ENABLE); isExecutionTracking = Boolean.valueOf(argsList[index + 1]); argumentList = removeItemFromIndex(index, argumentList); } if (argumentList.contains(Constants.TRACKING_CLIENT_SOCKET_PORT)) { int index = argumentList.indexOf(Constants.TRACKING_CLIENT_SOCKET_PORT); argumentList = removeItemFromIndex(index, argumentList); } argsList = argumentList.toArray(new String[argumentList.size()]); logger.debug("Execution tracking enabled - " + isExecutionTracking); logger.info("Tracking Client Port: " + trackingClientSocketPort); /** * Start new thread to run job */ final HydrographService execution = new HydrographService(); FutureTask task = hydrographMain.executeGraph(latch, jobId, argsList, execution, isExecutionTracking); hydrographMain.executorService = Executors.newSingleThreadExecutor(); hydrographMain.executorService.submit(task); if (isExecutionTracking) { //If tracking is enabled, start to post execution tracking status. final HydrographEngineCommunicatorSocket socket = new HydrographEngineCommunicatorSocket(execution); session = hydrographMain.connectToServer(socket, jobId, trackingClientSocketPort); hydrographMain.sendExecutionTrackingStatus(latch, session, jobId, timer, execution, socket); } //waiting for execute graph thread task.get(); } catch (Exception exp) { logger.info("Getting exception from HydrographMain"); throw new RuntimeException(exp); } finally { //cleanup threads --> executor thread and timer thread logger.info("HydrographMain releasing resources"); if (!hydrographMain.executorService.isShutdown() && !hydrographMain.executorService.isTerminated()) { hydrographMain.executorService.shutdown(); } timer.cancel(); } }
From source file:org.apache.metron.performance.load.LoadGenerator.java
public static void main(String[] args) throws Exception { CommandLine cli = LoadOptions.parse(new PosixParser(), args); EnumMap<LoadOptions, Optional<Object>> evaluatedArgs = LoadOptions.createConfig(cli); Map<String, Object> kafkaConfig = new HashMap<>(); kafkaConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); kafkaConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); kafkaConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); kafkaConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); if (LoadOptions.ZK.has(cli)) { String zkQuorum = (String) evaluatedArgs.get(LoadOptions.ZK).get(); kafkaConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, Joiner.on(",").join(KafkaUtils.INSTANCE.getBrokersFromZookeeper(zkQuorum))); }/* w w w. j a v a 2 s .c o m*/ String groupId = evaluatedArgs.get(LoadOptions.CONSUMER_GROUP).get().toString(); System.out.println("Consumer Group: " + groupId); kafkaConfig.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); if (LoadOptions.KAFKA_CONFIG.has(cli)) { kafkaConfig.putAll((Map<String, Object>) evaluatedArgs.get(LoadOptions.KAFKA_CONFIG).get()); } kafkaProducer = ThreadLocal.withInitial(() -> new KafkaProducer<>(kafkaConfig)); int numThreads = (int) evaluatedArgs.get(LoadOptions.NUM_THREADS).get(); System.out.println("Thread pool size: " + numThreads); pool = Executors.newFixedThreadPool(numThreads); Optional<Object> eps = evaluatedArgs.get(LoadOptions.EPS); Optional<Object> outputTopic = evaluatedArgs.get(LoadOptions.OUTPUT_TOPIC); Optional<Object> monitorTopic = evaluatedArgs.get(LoadOptions.MONITOR_TOPIC); long sendDelta = (long) evaluatedArgs.get(LoadOptions.SEND_DELTA).get(); long monitorDelta = (long) evaluatedArgs.get(LoadOptions.MONITOR_DELTA).get(); if ((eps.isPresent() && outputTopic.isPresent()) || monitorTopic.isPresent()) { Timer timer = new Timer(false); long startTimeMs = System.currentTimeMillis(); if (outputTopic.isPresent() && eps.isPresent()) { List<String> templates = (List<String>) evaluatedArgs.get(LoadOptions.TEMPLATE).get(); if (templates.isEmpty()) { System.out.println("Empty templates, so nothing to do."); return; } Optional<Object> biases = evaluatedArgs.get(LoadOptions.BIASED_SAMPLE); Sampler sampler = new UnbiasedSampler(); if (biases.isPresent()) { sampler = new BiasedSampler((List<Map.Entry<Integer, Integer>>) biases.get(), templates.size()); } MessageGenerator generator = new MessageGenerator(templates, sampler); Long targetLoad = (Long) eps.get(); int periodsPerSecond = (int) (1000 / sendDelta); long messagesPerPeriod = targetLoad / periodsPerSecond; String outputTopicStr = (String) outputTopic.get(); System.out.println( "Generating data to " + outputTopicStr + " at " + targetLoad + " events per second"); System.out.println("Sending " + messagesPerPeriod + " messages to " + outputTopicStr + " every " + sendDelta + "ms"); timer.scheduleAtFixedRate(new SendToKafka(outputTopicStr, messagesPerPeriod, numThreads, generator, pool, numSent, kafkaProducer), 0, sendDelta); } List<AbstractMonitor> monitors = new ArrayList<>(); if (outputTopic.isPresent() && monitorTopic.isPresent()) { System.out.println("Monitoring " + monitorTopic.get() + " every " + monitorDelta + " ms"); monitors.add(new EPSGeneratedMonitor(outputTopic, numSent)); monitors.add(new EPSThroughputWrittenMonitor(monitorTopic, kafkaConfig)); } else if (outputTopic.isPresent() && !monitorTopic.isPresent()) { System.out.println("Monitoring " + outputTopic.get() + " every " + monitorDelta + " ms"); monitors.add(new EPSGeneratedMonitor(outputTopic, numSent)); monitors.add(new EPSThroughputWrittenMonitor(outputTopic, kafkaConfig)); } else if (!outputTopic.isPresent() && monitorTopic.isPresent()) { System.out.println("Monitoring " + monitorTopic.get() + " every " + monitorDelta + " ms"); monitors.add(new EPSThroughputWrittenMonitor(monitorTopic, kafkaConfig)); } else if (!outputTopic.isPresent() && !monitorTopic.isPresent()) { System.out.println( "You have not specified an output topic or a monitoring topic, so I have nothing to do here."); } int lookback = (int) evaluatedArgs.get(LoadOptions.SUMMARY_LOOKBACK).get(); if (lookback > 0) { System.out.println("Summarizing over the last " + lookback + " monitoring periods (" + lookback * monitorDelta + "ms)"); } else { System.out.println("Turning off summarization."); } final CSVWriter csvWriter = new CSVWriter((File) evaluatedArgs.get(LoadOptions.CSV).orElse(null)); Writer writer = new Writer(monitors, lookback, new ArrayList<Consumer<Writable>>() { { add(new ConsoleWriter()); add(csvWriter); } }); timer.scheduleAtFixedRate(new MonitorTask(writer), 0, monitorDelta); Optional<Object> timeLimit = evaluatedArgs.get(LoadOptions.TIME_LIMIT); if (timeLimit.isPresent()) { System.out.println("Ending in " + timeLimit.get() + " ms."); timer.schedule(new TimerTask() { @Override public void run() { timer.cancel(); long durationS = (System.currentTimeMillis() - startTimeMs) / 1000; System.out.println("\nGenerated " + numSent.get() + " in " + durationS + " seconds."); csvWriter.close(); System.exit(0); } } , (Long) timeLimit.get()); } } }
From source file:org.apache.bookkeeper.benchmark.BenchThroughputLatency.java
@SuppressWarnings("deprecation") public static void main(String[] args) throws KeeperException, IOException, InterruptedException, ParseException, BKException { Options options = new Options(); options.addOption("time", true, "Running time (seconds), default 60"); options.addOption("entrysize", true, "Entry size (bytes), default 1024"); options.addOption("ensemble", true, "Ensemble size, default 3"); options.addOption("quorum", true, "Quorum size, default 2"); options.addOption("ackQuorum", true, "Ack quorum size, default is same as quorum"); options.addOption("throttle", true, "Max outstanding requests, default 10000"); options.addOption("ledgers", true, "Number of ledgers, default 1"); options.addOption("zookeeper", true, "Zookeeper ensemble, default \"localhost:2181\""); options.addOption("password", true, "Password used to create ledgers (default 'benchPasswd')"); options.addOption("coordnode", true, "Coordination znode for multi client benchmarks (optional)"); options.addOption("timeout", true, "Number of seconds after which to give up"); options.addOption("sockettimeout", true, "Socket timeout for bookkeeper client. In seconds. Default 5"); options.addOption("skipwarmup", false, "Skip warm up, default false"); options.addOption("sendlimit", true, "Max number of entries to send. Default 20000000"); options.addOption("latencyFile", true, "File to dump latencies. Default is latencyDump.dat"); options.addOption("help", false, "This message"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("BenchThroughputLatency <options>", options); System.exit(-1);//w w w .j a v a2s . c o m } long runningTime = Long.parseLong(cmd.getOptionValue("time", "60")); String servers = cmd.getOptionValue("zookeeper", "localhost:2181"); int entrysize = Integer.parseInt(cmd.getOptionValue("entrysize", "1024")); int ledgers = Integer.parseInt(cmd.getOptionValue("ledgers", "1")); int ensemble = Integer.parseInt(cmd.getOptionValue("ensemble", "3")); int quorum = Integer.parseInt(cmd.getOptionValue("quorum", "2")); int ackQuorum = quorum; if (cmd.hasOption("ackQuorum")) { ackQuorum = Integer.parseInt(cmd.getOptionValue("ackQuorum")); } int throttle = Integer.parseInt(cmd.getOptionValue("throttle", "10000")); int sendLimit = Integer.parseInt(cmd.getOptionValue("sendlimit", "20000000")); final int sockTimeout = Integer.parseInt(cmd.getOptionValue("sockettimeout", "5")); String coordinationZnode = cmd.getOptionValue("coordnode"); final byte[] passwd = cmd.getOptionValue("password", "benchPasswd").getBytes(UTF_8); String latencyFile = cmd.getOptionValue("latencyFile", "latencyDump.dat"); Timer timeouter = new Timer(); if (cmd.hasOption("timeout")) { final long timeout = Long.parseLong(cmd.getOptionValue("timeout", "360")) * 1000; timeouter.schedule(new TimerTask() { public void run() { System.err.println("Timing out benchmark after " + timeout + "ms"); System.exit(-1); } }, timeout); } LOG.warn("(Parameters received) running time: " + runningTime + ", entry size: " + entrysize + ", ensemble size: " + ensemble + ", quorum size: " + quorum + ", throttle: " + throttle + ", number of ledgers: " + ledgers + ", zk servers: " + servers + ", latency file: " + latencyFile); long totalTime = runningTime * 1000; // Do a warmup run Thread thread; byte data[] = new byte[entrysize]; Arrays.fill(data, (byte) 'x'); ClientConfiguration conf = new ClientConfiguration(); conf.setThrottleValue(throttle).setReadTimeout(sockTimeout).setZkServers(servers); if (!cmd.hasOption("skipwarmup")) { long throughput; LOG.info("Starting warmup"); throughput = warmUp(data, ledgers, ensemble, quorum, passwd, conf); LOG.info("Warmup tp: " + throughput); LOG.info("Warmup phase finished"); } // Now do the benchmark BenchThroughputLatency bench = new BenchThroughputLatency(ensemble, quorum, ackQuorum, passwd, ledgers, sendLimit, conf); bench.setEntryData(data); thread = new Thread(bench); ZooKeeper zk = null; if (coordinationZnode != null) { final CountDownLatch connectLatch = new CountDownLatch(1); zk = new ZooKeeper(servers, 15000, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { connectLatch.countDown(); } } }); if (!connectLatch.await(10, TimeUnit.SECONDS)) { LOG.error("Couldn't connect to zookeeper at " + servers); zk.close(); System.exit(-1); } final CountDownLatch latch = new CountDownLatch(1); LOG.info("Waiting for " + coordinationZnode); if (zk.exists(coordinationZnode, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == EventType.NodeCreated) { latch.countDown(); } } }) != null) { latch.countDown(); } latch.await(); LOG.info("Coordination znode created"); } thread.start(); Thread.sleep(totalTime); thread.interrupt(); thread.join(); LOG.info("Calculating percentiles"); int numlat = 0; for (int i = 0; i < bench.latencies.length; i++) { if (bench.latencies[i] > 0) { numlat++; } } int numcompletions = numlat; numlat = Math.min(bench.sendLimit, numlat); long[] latency = new long[numlat]; int j = 0; for (int i = 0; i < bench.latencies.length && j < numlat; i++) { if (bench.latencies[i] > 0) { latency[j++] = bench.latencies[i]; } } Arrays.sort(latency); long tp = (long) ((double) (numcompletions * 1000.0) / (double) bench.getDuration()); LOG.info(numcompletions + " completions in " + bench.getDuration() + " milliseconds: " + tp + " ops/sec"); if (zk != null) { zk.create(coordinationZnode + "/worker-", ("tp " + tp + " duration " + bench.getDuration()).getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); zk.close(); } // dump the latencies for later debugging (it will be sorted by entryid) OutputStream fos = new BufferedOutputStream(new FileOutputStream(latencyFile)); for (Long l : latency) { fos.write((Long.toString(l) + "\t" + (l / 1000000) + "ms\n").getBytes(UTF_8)); } fos.flush(); fos.close(); // now get the latencies LOG.info("99th percentile latency: {}", percentile(latency, 99)); LOG.info("95th percentile latency: {}", percentile(latency, 95)); bench.close(); timeouter.cancel(); }
From source file:org.apache.bookkeeper.benchmark.TestClient.java
/** * First says if entries should be written to BookKeeper (0) or to the local * disk (1). Second parameter is an integer defining the length of a ledger entry. * Third parameter is the number of writes. * * @param args//from ww w . java 2 s . com */ public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("length", true, "Length of packets being written. Default 1024"); options.addOption("target", true, "Target medium to write to. Options are bk, fs & hdfs. Default fs"); options.addOption("runfor", true, "Number of seconds to run for. Default 60"); options.addOption("path", true, "Path to write to. fs & hdfs only. Default /foobar"); options.addOption("zkservers", true, "ZooKeeper servers, comma separated. bk only. Default localhost:2181."); options.addOption("bkensemble", true, "BookKeeper ledger ensemble size. bk only. Default 3"); options.addOption("bkquorum", true, "BookKeeper ledger quorum size. bk only. Default 2"); options.addOption("bkthrottle", true, "BookKeeper throttle size. bk only. Default 10000"); options.addOption("sync", false, "Use synchronous writes with BookKeeper. bk only."); options.addOption("numconcurrent", true, "Number of concurrently clients. Default 1"); options.addOption("timeout", true, "Number of seconds after which to give up"); options.addOption("help", false, "This message"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("TestClient <options>", options); System.exit(-1); } int length = Integer.parseInt(cmd.getOptionValue("length", "1024")); String target = cmd.getOptionValue("target", "fs"); long runfor = Long.parseLong(cmd.getOptionValue("runfor", "60")) * 1000; StringBuilder sb = new StringBuilder(); while (length-- > 0) { sb.append('a'); } Timer timeouter = new Timer(); if (cmd.hasOption("timeout")) { final long timeout = Long.parseLong(cmd.getOptionValue("timeout", "360")) * 1000; timeouter.schedule(new TimerTask() { public void run() { System.err.println("Timing out benchmark after " + timeout + "ms"); System.exit(-1); } }, timeout); } BookKeeper bkc = null; try { int numFiles = Integer.parseInt(cmd.getOptionValue("numconcurrent", "1")); int numThreads = Math.min(numFiles, 1000); byte[] data = sb.toString().getBytes(UTF_8); long runid = System.currentTimeMillis(); List<Callable<Long>> clients = new ArrayList<Callable<Long>>(); if (target.equals("bk")) { String zkservers = cmd.getOptionValue("zkservers", "localhost:2181"); int bkensemble = Integer.parseInt(cmd.getOptionValue("bkensemble", "3")); int bkquorum = Integer.parseInt(cmd.getOptionValue("bkquorum", "2")); int bkthrottle = Integer.parseInt(cmd.getOptionValue("bkthrottle", "10000")); ClientConfiguration conf = new ClientConfiguration(); conf.setThrottleValue(bkthrottle); conf.setZkServers(zkservers); bkc = new BookKeeper(conf); List<LedgerHandle> handles = new ArrayList<LedgerHandle>(); for (int i = 0; i < numFiles; i++) { handles.add(bkc.createLedger(bkensemble, bkquorum, DigestType.CRC32, new byte[] { 'a', 'b' })); } for (int i = 0; i < numFiles; i++) { clients.add(new BKClient(handles, data, runfor, cmd.hasOption("sync"))); } } else if (target.equals("hdfs")) { FileSystem fs = FileSystem.get(new Configuration()); LOG.info("Default replication for HDFS: {}", fs.getDefaultReplication()); List<FSDataOutputStream> streams = new ArrayList<FSDataOutputStream>(); for (int i = 0; i < numFiles; i++) { String path = cmd.getOptionValue("path", "/foobar"); streams.add(fs.create(new Path(path + runid + "_" + i))); } for (int i = 0; i < numThreads; i++) { clients.add(new HDFSClient(streams, data, runfor)); } } else if (target.equals("fs")) { List<FileOutputStream> streams = new ArrayList<FileOutputStream>(); for (int i = 0; i < numFiles; i++) { String path = cmd.getOptionValue("path", "/foobar " + i); streams.add(new FileOutputStream(path + runid + "_" + i)); } for (int i = 0; i < numThreads; i++) { clients.add(new FileClient(streams, data, runfor)); } } else { LOG.error("Unknown option: " + target); throw new IllegalArgumentException("Unknown target " + target); } ExecutorService executor = Executors.newFixedThreadPool(numThreads); long start = System.currentTimeMillis(); List<Future<Long>> results = executor.invokeAll(clients, 10, TimeUnit.MINUTES); long end = System.currentTimeMillis(); long count = 0; for (Future<Long> r : results) { if (!r.isDone()) { LOG.warn("Job didn't complete"); System.exit(2); } long c = r.get(); if (c == 0) { LOG.warn("Task didn't complete"); } count += c; } long time = end - start; LOG.info("Finished processing writes (ms): {} TPT: {} op/s", time, count / ((double) time / 1000)); executor.shutdown(); } catch (ExecutionException ee) { LOG.error("Exception in worker", ee); } catch (KeeperException ke) { LOG.error("Error accessing zookeeper", ke); } catch (BKException e) { LOG.error("Error accessing bookkeeper", e); } catch (IOException ioe) { LOG.error("I/O exception during benchmark", ioe); } catch (InterruptedException ie) { LOG.error("Benchmark interrupted", ie); } finally { if (bkc != null) { try { bkc.close(); } catch (BKException bke) { LOG.error("Error closing bookkeeper client", bke); } catch (InterruptedException ie) { LOG.warn("Interrupted closing bookkeeper client", ie); } } } timeouter.cancel(); }
From source file:Main.java
public static void clearTimeOut(Timer timer) { if (timer != null) { timer.cancel(); } }
From source file:Main.java
public static void clearInterval(Timer timer) { if (timer != null) { timer.cancel(); } }