List of usage examples for java.util Timer Timer
public Timer(String name, boolean isDaemon)
From source file:com.alibaba.rocketmq.example.benchmark.Consumer.java
public static void main(String[] args) throws MQClientException { Options options = ServerUtil.buildCommandlineOptions(new Options()); CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args, buildCommandlineOptions(options), new PosixParser()); if (null == commandLine) { System.exit(-1);/*from w w w.j a v a 2s . c o m*/ } final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest"; final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim() : "benchmark_consumer"; final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true"; String group = groupPrefix; if (Boolean.parseBoolean(isPrefixEnable)) { group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100); } System.out.printf("topic %s group %s prefix %s%n", topic, group, isPrefixEnable); final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer(); final Timer timer = new Timer("BenchmarkTimerThread", true); final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { snapshotList.addLast(statsBenchmarkConsumer.createSnapshot()); if (snapshotList.size() > 10) { snapshotList.removeFirst(); } } }, 1000, 1000); timer.scheduleAtFixedRate(new TimerTask() { private void printStats() { if (snapshotList.size() >= 10) { Long[] begin = snapshotList.getFirst(); Long[] end = snapshotList.getLast(); final long consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L); final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]); final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]); System.out.printf( "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n", consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, 10000, 10000); DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group); consumer.setInstanceName(Long.toString(System.currentTimeMillis())); consumer.subscribe(topic, "*"); consumer.registerMessageListener(new MessageListenerConcurrently() { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) { MessageExt msg = msgs.get(0); long now = System.currentTimeMillis(); statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet(); long born2ConsumerRT = now - msg.getBornTimestamp(); statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT); long store2ConsumerRT = now - msg.getStoreTimestamp(); statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT); compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT); compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT); return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } }); consumer.start(); System.out.printf("Consumer Started.%n"); }
From source file:com.alibaba.rocketmq.example.benchmark.Producer.java
public static void main(String[] args) throws MQClientException, UnsupportedEncodingException { Options options = ServerUtil.buildCommandlineOptions(new Options()); CommandLine commandLine = ServerUtil.parseCmdLine("producer", args, buildCommandlineOptions(options), new PosixParser()); if (null == commandLine) { System.exit(-1);/*w w w .j av a2 s . co m*/ } final int threadCount = commandLine.hasOption('t') ? Integer.parseInt(commandLine.getOptionValue('t')) : 64; final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; final boolean keyEnable = commandLine.hasOption('k') ? Boolean.parseBoolean(commandLine.getOptionValue('k')) : false; System.out.printf("threadCount %d messageSize %d keyEnable %s%n", threadCount, messageSize, keyEnable); final Logger log = ClientLogger.getLog(); final Message msg = buildMessage(messageSize); final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount); final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer(); final Timer timer = new Timer("BenchmarkTimerThread", true); final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { snapshotList.addLast(statsBenchmark.createSnapshot()); if (snapshotList.size() > 10) { snapshotList.removeFirst(); } } }, 1000, 1000); timer.scheduleAtFixedRate(new TimerTask() { private void printStats() { if (snapshotList.size() >= 10) { Long[] begin = snapshotList.getFirst(); Long[] end = snapshotList.getLast(); final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L); final double averageRT = ((end[5] - begin[5]) / (double) (end[3] - begin[3])); System.out.printf( "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n"// , sendTps// , statsBenchmark.getSendMessageMaxRT().get()// , averageRT// , end[2]// , end[4]// ); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, 10000, 10000); final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer"); producer.setInstanceName(Long.toString(System.currentTimeMillis())); if (commandLine.hasOption('n')) { String ns = commandLine.getOptionValue('n'); producer.setNamesrvAddr(ns); } producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE); producer.start(); for (int i = 0; i < threadCount; i++) { sendThreadPool.execute(new Runnable() { @Override public void run() { while (true) { try { final long beginTimestamp = System.currentTimeMillis(); if (keyEnable) { msg.setKeys(String.valueOf(beginTimestamp / 1000)); } producer.send(msg); statsBenchmark.getSendRequestSuccessCount().incrementAndGet(); statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet(); final long currentRT = System.currentTimeMillis() - beginTimestamp; statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT); long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); while (currentRT > prevMaxRT) { boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT, currentRT); if (updated) break; prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); } } catch (RemotingException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); try { Thread.sleep(3000); } catch (InterruptedException e1) { } } catch (InterruptedException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); try { Thread.sleep(3000); } catch (InterruptedException e1) { } } catch (MQClientException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); } catch (MQBrokerException e) { statsBenchmark.getReceiveResponseFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); try { Thread.sleep(3000); } catch (InterruptedException e1) { } } } } }); } }
From source file:com.damon.rocketmq.example.benchmark.Producer.java
public static void main(String[] args) throws MQClientException, UnsupportedEncodingException { Options options = ServerUtil.buildCommandlineOptions(new Options()); CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkProducer", args, buildCommandlineOptions(options), new PosixParser()); if (null == commandLine) { System.exit(-1);/*from w w w . j a v a 2s . c om*/ } final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest"; final int threadCount = commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 64; final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; final boolean keyEnable = commandLine.hasOption('k') && Boolean.parseBoolean(commandLine.getOptionValue('k')); System.out.printf("topic %s threadCount %d messageSize %d keyEnable %s%n", topic, threadCount, messageSize, keyEnable); final Logger log = ClientLogger.getLog(); final Message msg = buildMessage(messageSize, topic); final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount); final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer(); final Timer timer = new Timer("BenchmarkTimerThread", true); final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { snapshotList.addLast(statsBenchmark.createSnapshot()); if (snapshotList.size() > 10) { snapshotList.removeFirst(); } } }, 1000, 1000); timer.scheduleAtFixedRate(new TimerTask() { private void printStats() { if (snapshotList.size() >= 10) { Long[] begin = snapshotList.getFirst(); Long[] end = snapshotList.getLast(); final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L); final double averageRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]); System.out.printf( "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n", sendTps, statsBenchmark.getSendMessageMaxRT().get(), averageRT, end[2], end[4]); } } @Override public void run() { try { this.printStats(); } catch (Exception e) { e.printStackTrace(); } } }, 10000, 10000); final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer"); producer.setInstanceName(Long.toString(System.currentTimeMillis())); if (commandLine.hasOption('n')) { String ns = commandLine.getOptionValue('n'); producer.setNamesrvAddr(ns); } producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE); producer.start(); for (int i = 0; i < threadCount; i++) { sendThreadPool.execute(new Runnable() { @Override public void run() { while (true) { try { final long beginTimestamp = System.currentTimeMillis(); if (keyEnable) { msg.setKeys(String.valueOf(beginTimestamp / 1000)); } producer.send(msg); statsBenchmark.getSendRequestSuccessCount().incrementAndGet(); statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet(); final long currentRT = System.currentTimeMillis() - beginTimestamp; statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT); long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); while (currentRT > prevMaxRT) { boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT, currentRT); if (updated) break; prevMaxRT = statsBenchmark.getSendMessageMaxRT().get(); } } catch (RemotingException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); try { Thread.sleep(3000); } catch (InterruptedException ignored) { } } catch (InterruptedException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); try { Thread.sleep(3000); } catch (InterruptedException e1) { } } catch (MQClientException e) { statsBenchmark.getSendRequestFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); } catch (MQBrokerException e) { statsBenchmark.getReceiveResponseFailedCount().incrementAndGet(); log.error("[BENCHMARK_PRODUCER] Send Exception", e); try { Thread.sleep(3000); } catch (InterruptedException ignored) { } } } } }); } }
From source file:Main.java
public Main(int seconds) { timer = new Timer("MyTimer", true); timer.schedule(new RemindTask(), seconds * 1000); }
From source file:com.offbynull.portmapper.common.ProcessUtils.java
/** * Run a process and dump the stdout stream to a string. * @param timeout maximum amount of time the process can take to run * @param command command//w w w .ja v a2 s . c o m * @param args arguments * @return stdout from the process dumped to a string * @throws IOException if the process encounters an error * @throws NullPointerException if any arguments are {@code null} or contains {@code null} * @throws IllegalArgumentException any numeric argument is negative */ public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException { Validate.notNull(command); Validate.noNullElements(args); Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout); String[] pbCmd = new String[args.length + 1]; pbCmd[0] = command; System.arraycopy(args, 0, pbCmd, 1, args.length); ProcessBuilder builder = new ProcessBuilder(pbCmd); final AtomicBoolean failedFlag = new AtomicBoolean(); Timer timer = new Timer("Process timeout timer", true); Process proc = null; try { proc = builder.start(); final Process finalProc = proc; timer.schedule(new TimerTask() { @Override public void run() { failedFlag.set(true); finalProc.destroy(); } }, timeout); String ret = IOUtils.toString(proc.getInputStream()); if (failedFlag.get()) { throw new IOException("Process failed"); } return ret; } finally { if (proc != null) { proc.destroy(); } timer.cancel(); timer.purge(); } }
From source file:de.tor.tribes.util.ClipboardWatch.java
private synchronized void playNotification() { if (!Boolean.parseBoolean(GlobalOptions.getProperty("clipboard.notification"))) { return;/* www . ja va 2s. c o m*/ } Timer t = new Timer("ClipboardNotification", true); t.schedule(new TimerTask() { @Override public void run() { if (clip != null) {//reset clip clip.stop(); clip.setMicrosecondPosition(0); } if (ac != null) { ac.stop(); } try { if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) { if (clip == null) { clip = AudioSystem.getClip(); AudioInputStream inputStream = AudioSystem .getAudioInputStream(ClockFrame.class.getResourceAsStream("/res/Ding.wav")); clip.open(inputStream); } clip.start(); } else { if (ac == null) { ac = Applet.newAudioClip(ClockFrame.class.getResource("/res/Ding.wav")); } ac.play(); } } catch (Exception e) { logger.error("Failed to play notification", e); } } }, 0); }
From source file:fr.calamus.common.db.core.DbAccessFactory.java
private static void launchInstancesObserver() { /*Thread run = new Thread() { @Override/* w ww. ja v a 2s.co m*/ public void run() { while (true) { try { Thread.currentThread().wait(10000); synchronized (instances) { long now = System.currentTimeMillis(); List<String> toRemove = new ArrayList<>(); for (String id : instances.keySet()) { AdeDbFactory db = instances.get(id); if (db == null || now > db.lastUsedTime() + db.adeTimeOut()) { toRemove.add(id); } } log.debug("removing " + toRemove.size() + " instance(s)"); for (String id : toRemove) { instances.remove(id); } } } catch (InterruptedException ex) { log.warn(ex); } } } }; run.start();*/ Timer timer = new Timer("DbAccessFactory-instancesRemover", true); TimerTask task = new TimerTask() { @Override public void run() { synchronized (instances) { long now = System.currentTimeMillis(); List<String> toRemove = new ArrayList<>(); for (String id : instances.keySet()) { DbAccess db = instances.get(id); if (id != null && (db == null || now > db.lastUsedTime() + timeOut())) { toRemove.add(id); } } for (String id : toRemove) { instances.remove(id); } if (toRemove.size() > 0) log.debug("removed " + toRemove.size() + " instance(s); remaining " + instances.size()); } } }; timer.schedule(task, 30000, 10000); }
From source file:com.lfv.lanzius.application.SoundClip.java
public SoundClip(Mixer outputMixer, String filenameAlternativeA, String filenameAlternativeB, int periodMillis, float volumeAdjustment) { log = LogFactory.getLog(getClass()); if (soundTimer == null) soundTimer = new Timer("Ssoundclip", true); boolean altA = true; this.periodMillis = periodMillis; this.volumeAdjustment = volumeAdjustment; // Try to open the first alternative clip try {// w w w.j a v a2 s .c o m stream = AudioSystem.getAudioInputStream(new File(filenameAlternativeA)); DataLine.Info dataLineInfo = new DataLine.Info(Clip.class, stream.getFormat()); clip = (Clip) outputMixer.getLine(dataLineInfo); clip.open(stream); } catch (Exception ex) { // The first alternative clip could not be opened, try with second alternative try { if (stream != null) stream.close(); if (filenameAlternativeB == null) throw ex; stream = AudioSystem.getAudioInputStream(new File(filenameAlternativeB)); DataLine.Info dataLineInfo = new DataLine.Info(Clip.class, stream.getFormat()); clip = (Clip) outputMixer.getLine(dataLineInfo); clip.open(stream); altA = false; } catch (Exception ex2) { log.error("Unable to get stream for file " + filenameAlternativeA); log.error("Unable to get stream for file " + filenameAlternativeB); if (stream != null) { try { stream.close(); } catch (IOException ex3) { log.error("Error closing stream ", ex3); } } stream = null; return; } } int clipLength = (int) (clip.getMicrosecondLength() / 1000L); log.debug("Loading sound clip " + (altA ? filenameAlternativeA : filenameAlternativeB) + " (" + clipLength + "ms)"); // Check length if (periodMillis < clipLength) throw new IllegalArgumentException("The periodMillis value must be larger than length of the clip"); }
From source file:fr.aliasource.webmail.pool.Pool.java
public Pool(String poolId, IPoolableObjectFactory<T> factory, int poolSize, String destroyMethodName, long keepAlivePeriod) { this.logger = LogFactory.getLog(getClass()); this.poolId = poolId; this.objectsInUse = Collections.synchronizedSet(new HashSet<T>()); this.destroyMethod = destroyMethodName; this.availableObjects = new LinkedBlockingQueue<T>(poolSize); for (int i = 0; i < poolSize; i++) { logger.info(poolId + ": Adding pooled object..."); availableObjects.add(factory.createNewObject()); logger.info(poolId + ": Pooled object added."); }/*from w w w . j ava2s . c o m*/ keepAliveTimer = new Timer(poolId + "-keepalive-timer", true); KeepAliveTask<T> kaTsk = new KeepAliveTask<T>(availableObjects, factory, this); keepAliveTimer.scheduleAtFixedRate(kaTsk, 10000, keepAlivePeriod); }
From source file:fr.calamus.common.db.core.DbCentralFactory.java
protected static void launchInstancesObserver() { if (!instancesObserverIsLaunched) { Timer timer = new Timer("DbFactory-instancesRemover", true); TimerTask task = new TimerTask() { @Override//from w ww . ja va 2 s . c om public void run() { synchronized (instances) { long now = System.currentTimeMillis(); List<String> toRemove = new ArrayList<>(); for (String id : instances.keySet()) { DbCentralFactory db = instances.get(id); if (id != null && (db == null || now > db.lastUsedTime() + db.cnxTimeOut())) { toRemove.add(id); } } for (String id : toRemove) { DbCentralFactory db = instances.get(id); if (db != null) { db.close(); } instances.remove(id); } if (toRemove.size() > 0) { log.debug("removed " + toRemove.size() + " instance(s); remaining " + instances.size()); } } } }; timer.schedule(task, 30000, 10000); instancesObserverIsLaunched = true; } }