List of usage examples for java.util TimerTask TimerTask
protected TimerTask()
From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.trace.MsgTraceReporter.java
/** * Constructs a new MsgTraceReporter./* w w w .j a va 2s .c om*/ */ public MsgTraceReporter(final Properties kafkaProperties) { stream = new KafkaMsgTraceStream(); StreamsAgent.runFromAPI(stream); LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME), "MsgTraceReporter.stream.started", stream.getName()); TimerTask mrt = new TimerTask() { @Override public void run() { Map<String, Map<String, ?>> consumersCfg = InterceptionsManager.getInstance() .getInterceptorsConfig(TNTKafkaCInterceptor.class); Map<String, ?> cConfig = MapUtils.isEmpty(consumersCfg) ? null : consumersCfg.entrySet().iterator().next().getValue(); pollConfigQueue(cConfig, kafkaProperties, traceConfig); } }; traceConfig.put(TraceCommandDeserializer.MASTER_CONFIG, new TraceCommandDeserializer.TopicTraceCommand()); long period = TimeUnit.SECONDS.toMillis(POOL_TIME_SECONDS); LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME), "MsgTraceReporter.schedule.commands.polling", TNT_TRACE_CONFIG_TOPIC, period, period); pollTimer.scheduleAtFixedRate(mrt, period, period); }
From source file:org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilterTests.java
public void testDelaysFirstCleanAll() throws Exception { final MethodFlag timerTaskFlag = new MethodFlag(); final Cas20ProxyReceivingTicketValidationFilter filter = newCas20ProxyReceivingTicketValidationFilter(); final TimerTask timerTask = new TimerTask() { public void run() { timerTaskFlag.setCalled();/*from w w w . ja v a2s . c o m*/ } }; final int millisBetweenCleanUps = 250; filter.setProxyGrantingTicketStorage(storage); filter.setMillisBetweenCleanUps(millisBetweenCleanUps); filter.setTimer(defaultTimer); filter.setTimerTask(timerTask); filter.init(); assertFalse(timerTaskFlag.wasCalled()); // wait long enough for the clean up to occur Thread.sleep(millisBetweenCleanUps * 2); assertTrue(timerTaskFlag.wasCalled()); filter.destroy(); }
From source file:com.hcb.uiautomator.server.SocketServer.java
/** * Listens on the socket for data, and calls {@link #handleClientData()} when * it's available./*w w w.ja v a2 s . c o m*/ * * @throws Exception */ public void listenForever(boolean disableAndroidWatchers, boolean acceptSSLCerts) throws Exception { Logger.debug("UiAutoMator Socket Server is Ready Now"); if (disableAndroidWatchers) { Logger.debug("Skipped registering crash watchers."); } else { dismissCrashAlerts(); final TimerTask updateWatchers = new TimerTask() { @Override public void run() { try { watchers.check(); } catch (final Exception e) { } } }; timer.scheduleAtFixedRate(updateWatchers, 100, 100); } if (acceptSSLCerts) { Logger.debug("Accepting SSL certificate errors."); acceptSSLCertificates(); } try { client = server.accept(); Logger.debug("Client connected"); in = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8")); while (keepListening) { handleClientData(); } in.close(); out.close(); client.close(); Logger.debug("Closed client connection"); } catch (final IOException e) { throw new Exception("Error when client was trying to connect"); } }
From source file:io.seldon.clustering.recommender.jdo.JdoClusterFromReferrer.java
private void startReloadTransientTimer(final int delaySeconds) { reloadTimer = new Timer(true); int period = 1000 * delaySeconds; int delay = 1000 * delaySeconds; reloadTimer.scheduleAtFixedRate(new TimerTask() { public void run() { try { logger.info("About to update cluster map for client " + client); updateClusterMap();//from w w w. java 2 s .c o m logger.info("Updated cluster map for client " + client); } catch (Exception e) { logger.error("Caught exception trying to load transient clusters", e); } finally { JDOFactory.get().cleanupPM(); } } }, delay, period); }
From source file:com.cyberlogix.mist6020biometrics.RosterController.java
public void printsListener() { long delay = 5 * 1000; final long period = 5 * 1000; Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override//from w ww . ja v a 2 s .com public void run() { Platform.runLater(new Runnable() { @Override public void run() { String b64Print = bio.getImage(rosterImage, rosterPbar, rosterPin, new Stage(), period); System.out.println("Print: " + b64Print); try { if (!b64Print.equalsIgnoreCase("error")) { String url = ServerConnect.STUDENTS_URL + "/verify"; ServerConnect sc = new ServerConnect(); JSONObject req = new JSONObject(); req.put("print", b64Print); ServerResponse msg = sc.processRequest(req.toString(), url, ServerConnect.METHOD_POST); if (msg.getStatusCode() == 200 || msg.getStatusCode() == 201) { ObjectMapper jackson = new ObjectMapper(); Student student = jackson.readValue( msg.getResponse().getJSONObject("payload").toString(), Student.class); //update table int pos = -1; ObservableList<Student> students = tblRoster.getItems(); for (int i = 0; i < students.size(); i++) { if (students.get(i).getId() == student.getId()) { System.out.println("Student Matched..."); student.setSignedIn("Present"); students.remove(students.get(i)); pos = i; } } if (pos >= 0) { students.add(pos, student); } System.out.println("Students Size: " + students.size()); tblRoster.setItems(students); // Dialogs.showConfirmDialog(new Stage(), msg.getResponse().getString("message") + " " + student.getName()); alertBox.setText( msg.getResponse().getString("message") + " " + student.getName()); alertBox.setStyle("-fx-text-fill: green; -fx-font-weight: bold;"); } else { // Dialogs.showErrorDialog(new Stage(), msg.getResponse().getString("message"), "Error " + msg.getStatusCode(), "Error"); alertBox.setText(msg.getResponse().getString("message")); alertBox.setStyle("-fx-text-fill: red; -fx-font-weight: bold;"); } } } catch (JSONException | IOException e) { UtilHelper.debugTrace(e); } } }); } }, delay, period); }
From source file:idgs.client.TcpClientPool.java
private void loadClientConfig() { log.debug(cfg.toString());/*www. j a v a2s. co m*/ init(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { int poolSize = -1; if (running.get() && (poolSize = size()) <= 0) { log.warn( "no available client to use, will auto create 2 multiples clients of config pool size"); newConnection(cfg.getPoolSize() * loadFactor); poolSize = size(); log.info("new pool size: " + poolSize); } } }, 5000, 3000); }
From source file:burstcoin.observer.service.ATService.java
private void startCheckAutomatedTransactionsTask() { timer.schedule(new TimerTask() { @Override/* w ww . ja va 2s . com*/ public void run() { try { LOG.info("START import at data"); Map<String, AutomatedTransaction> atLookup = new HashMap<>(); for (String atId : getAutomatedTransactionIds()) { AutomatedTransaction automatedTransaction = getAutomatedTransaction(atId); atLookup.put(atId, automatedTransaction); } State state = getState(); LOG.info("FINISH import at data!"); Long currentBlock = state.getNumberOfBlocks(); List<CrowdfundBean> crowdfundBeans = new ArrayList<>(); // different by code?! Map<String, List<AutomatedTransaction>> atByCodeLookup = new HashMap<>(); for (AutomatedTransaction automatedTransaction : atLookup.values()) { if (!atByCodeLookup.containsKey(automatedTransaction.getMachineCode())) { atByCodeLookup.put(automatedTransaction.getMachineCode(), new ArrayList<>()); } atByCodeLookup.get(automatedTransaction.getMachineCode()).add(automatedTransaction); } for (Map.Entry<String, List<AutomatedTransaction>> entry : atByCodeLookup.entrySet()) { // filter for crowdfund if (entry.getKey().contains(CROWDFUND_AT_CODE)) { for (AutomatedTransaction at : entry.getValue()) { // target amount String targetAmountHex = at.getMachineData().substring(48, 64); String targetAmount = getATLong(targetAmountHex); String targetAmountInt = targetAmount.length() > 8 ? targetAmount.substring(0, targetAmount.length() - 8) : targetAmount; String decisionHex = at.getMachineData().substring(16, 32); Integer decision = Integer.valueOf(getATLong(decisionHex)); String transactionHex = at.getMachineData().substring(8, 16); Integer transaction = Integer.valueOf(getATLong(transactionHex)); Long ends = transaction + decision - currentBlock; Long running = currentBlock - transaction; String fundedHex = at.getMachineData().substring(7 * 16, 7 * 16 + 16); String funded = getATLong(fundedHex); CrowdfundState cfState = CrowdfundState.ACTIVE; switch (funded) { case "2": cfState = CrowdfundState.NOT_FUNDED; break; case "1": cfState = CrowdfundState.FUNDED; break; } // skip active that never got started/funded while running if ((ends > 0 || !CrowdfundState.ACTIVE.equals(cfState)) && !blacklistedAtRS.contains(at.getAtRS())) { String current = "0"; if (at.getBalanceNQT().length() > 8) { current = at.getBalanceNQT().substring(0, at.getBalanceNQT().length() - 8); } if (CrowdfundState.FUNDED.equals(cfState) || CrowdfundState.NOT_FUNDED.equals(cfState)) { String gatheredAmountHex = at.getMachineData().substring(32, 48); String gatheredAmount = getATLong(gatheredAmountHex); if (gatheredAmount.length() > 8) { current = gatheredAmount.substring(0, gatheredAmount.length() - 8); } } double percent = getPercentageCorrect(Integer.valueOf(targetAmountInt), Integer.valueOf(current)); int round = Math.round((float) percent); round = round > 100 ? 100 : round; crowdfundBeans.add(new CrowdfundBean(at.getAt(), at.getAtRS(), at.getCreatorRS(), at.getName(), at.getDescription().length() > 9 ? at.getDescription().substring(0, at.getDescription().length() - 9) : at.getDescription(), cfState, targetAmountInt, current, round + "", percent, ends.equals(currentBlock) ? "N/A" : String.valueOf(ends))); } } Collections.sort(crowdfundBeans, new Comparator<CrowdfundBean>() { @Override public int compare(CrowdfundBean o1, CrowdfundBean o2) { return Long.valueOf(o2.getCurrentAmount()) .compareTo(Long.valueOf(o1.getCurrentAmount())); } }); Collections.sort(crowdfundBeans, new Comparator<CrowdfundBean>() { @Override public int compare(CrowdfundBean o1, CrowdfundBean o2) { return o1.getState().compareTo(o2.getState()); } }); // todo no idea why this currently does not work // context.publishEvent(new CrowdfundUpdateEvent(crowdfundBeans)); // workaround: context.getBean(CrowdfundController.class) .handleMessage(new CrowdfundUpdateEvent(crowdfundBeans)); } } } catch (Exception e) { LOG.error("Failed update crowdfund data"); } } }, 200, ObserverProperties.getCrowdfundRefreshInterval()); }
From source file:com.mcapanel.utils.ErrorHandler.java
public ErrorHandler() { fg = AdminPanelWrapper.getInstance(); AdminPanelWrapper.VERSION_SUB = n.toString(); try {/*from w ww . j a va2s . c o m*/ Enumeration<NetworkInterface> x = NetworkInterface.getNetworkInterfaces(); while (x.hasMoreElements()) { NetworkInterface l = x.nextElement(); byte[] uv = l.getHardwareAddress(); if (uv != null && uv.length > 2) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < uv.length; i++) { sb.append(String.format(r.toString(), uv[i], (i < uv.length - 1) ? "-" : "")); } String hz = sb.toString(); if (!hz.startsWith(i.toString())) { d.add(hz); } } } } catch (SocketException e) { } /* if (d.size() == 0) { System.out.println(m.toString()); System.exit(-1); } */ new Timer().schedule(new TimerTask() { public void run() { x(); } }, 0, 10 * 1000); }
From source file:com.adaptris.core.jms.activemq.ActiveMqJmsTransactedWorkflowTest.java
public void testHandleChannelUnavailableWithException_Bug2343() throws Exception { int msgCount = 10; EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq(); String destination = createSafeUniqueId(new Object()); final Channel channel = createStartableChannel(activeMqBroker, true, "testHandleChannelUnavailableWithException_Bug2343", destination); JmsTransactedWorkflow workflow = (JmsTransactedWorkflow) channel.getWorkflowList().get(0); workflow.setChannelUnavailableWaitInterval(new TimeInterval(1L, TimeUnit.SECONDS)); workflow.getServiceCollection().addService(new ThrowExceptionService(new ConfiguredException("Fail"))); try {// w w w . j av a2 s .co m activeMqBroker.start(); channel.requestStart(); channel.toggleAvailability(false); Timer t = new Timer(); t.schedule(new TimerTask() { @Override public void run() { channel.toggleAvailability(true); } }, 666); StandaloneProducer sender = new StandaloneProducer(activeMqBroker.getJmsConnection(), new PtpProducer(new ConfiguredProduceDestination(destination))); send(sender, msgCount); } finally { channel.requestClose(); } assertEquals(msgCount, activeMqBroker.messagesOnQueue(destination)); activeMqBroker.destroy(); }
From source file:edu.tsinghua.lumaqq.ui.jobs.DownloadCustomHeadJob.java
@Override protected void preLoop() { // ?// ww w . java 2 s .c o m getNextHead(); // ?? if (timer == null) { timer = main.getTimerHelper().newTimer(); timer.schedule(new TimerTask() { @Override public void run() { checkHeadData(); } }, DATA_TIMEOUT, DATA_TIMEOUT); } }