List of usage examples for java.util TimerTask TimerTask
protected TimerTask()
From source file:esg.node.components.registry.ESGFRegistry.java
private void startRegistry() { //---------------------------------- log.info("Loading and Initializing..."); try {//from ww w.j ava2 s. c o m //gleaner.loadMyRegistration(); gleaner.createMyRegistration().saveRegistration(); } catch (ESGFRegistryException e) { log.warn(e.getMessage()); gleaner.createMyRegistration(); } Set<Node> loadedNodes = new TreeSet<Node>(nodecomp); loadedNodes.addAll(gleaner.getMyRegistration().getNode()); enqueueESGEvent(new ESGEvent(this, new RegistryUpdateDigest(gleaner.toString(), gleaner.getMyChecksum(), loadedNodes), "Initializing...")); lastDispatchTime.set((new Date()).getTime()); //---------------------------------- log.trace("Launching registry timer"); long delay = Long.parseLong(props.getProperty("registry.initialDelay", "10")); final long period = Long.parseLong(props.getProperty("registry.period", "300")); //every 5 mins log.debug("registry delay: " + delay + " sec"); log.debug("registry period: " + period + " sec"); Timer timer = new Timer("Quiescence-Reg-Repost-Timer"); timer.schedule(new TimerTask() { public final void run() { //If I have not dispatched any information to //another peer in "period" seconds then touch the //registry (give a new timestamp and thus a new //checksum) and send out to share my view with //others. The idea here is to only send out your //state if you have been inactive for more than //"period" time - anecdotal evidence that the //network has reached quiescence. This avoids the //case where some node has already pushed their //state after quiescense and as such starts the //gossip dominoes, which gets here and you send //out your state, but without this conditional //here, then I would in turn send out my state //after the blind elapsing of the period and the //do the gossip cascade again... it makes for a //noisier network. So now nodes will deal with //one cascade at a time-ish. ;-) //Sidebar: There could potentially cause a race condition on //lastDispatchTime since longs are not required to //be dealt with in an atomic way by the VM, but it //won't hurt a thing. //-gavin Date now = new Date(); long delta = (now.getTime() - lastDispatchTime.longValue()); if (delta > (period * 1000)) { if (!ESGFRegistry.this.isBusy) { ESGFRegistry.this.isBusy = true; synchronized (gleaner) { //"touch" the registration.xml file (update timestamp via call to createMyRegistration, and resave) log.debug("re-posting registration..."); gleaner.saveRegistration(); enqueueESGEvent( new ESGEvent( this, new RegistryUpdateDigest(gleaner.toString(), gleaner.getMyChecksum(), new HashSet<Node>()), "Re-Posting Registration State")); lastDispatchTime.set((new Date()).getTime()); } ESGFRegistry.this.isBusy = false; } } else { log.debug("Won't re-send state - too soon after last dispatch (quiescence period " + period + "secs, was not reached [" + (delta / 1000) + "secs] elapsed)"); } } }, delay * 1000, period * 1000); }
From source file:esg.node.components.metrics.ESGMetrics.java
private void startMetricsCollection() { log.trace("launching node metrics timer"); long delay = Long.parseLong(props.getProperty("metrics.initialDelay")); long period = Long.parseLong(props.getProperty("metrics.period")); log.trace("metrics delay: " + delay + " sec"); log.trace("metrics period: " + period + " sec"); Timer timer = new Timer(); timer.schedule(new TimerTask() { public final void run() { //log.trace("Checking for new datanode information... [busy? "+ESGMetrics.this.isBusy+"]"); if (!ESGMetrics.this.isBusy) { ESGMetrics.this.isBusy = true; if (fetchNodeStats()) { metricsDAO.markLastCompletionTime(); }/*www.j a v a 2s . c o m*/ ESGMetrics.this.isBusy = false; } } }, delay * 1000, period * 1000); }
From source file:esg.node.connection.ESGConnectionManager.java
private void periodicallyPingToPeers() { log.trace("Launching ping timer..."); long delay = Long.parseLong(props.getProperty("conn.ping.initialDelay", "5")); long period = Long.parseLong(props.getProperty("conn.ping.period", "30")); log.trace("connection ping delay: " + delay + " sec"); log.trace("connection ping period: " + period + " sec"); Timer timer = new Timer("Peer-Sweep-Timer"); timer.schedule(new TimerTask() { public final void run() { ESGConnectionManager.this.pingToPeers(); }/*from w w w .j a v a2 s. c o m*/ }, delay * 1000, period * 1000); }
From source file:com.googlecode.fascinator.portal.HouseKeeper.java
/** * Start thread running/* w w w . j ava 2 s . c o m*/ * */ @Override public void run() { openLog(); try { globalConfig = new JsonSimpleConfig(); // Get a connection to the broker String brokerUrl = globalConfig.getString(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL, "messaging", "url"); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); connection = connectionFactory.createConnection(); // Sessions are not thread safe, to send a message outside // of the onMessage() callback you need another session. cSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); pSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = cSession.createQueue(QUEUE_ID); consumer = cSession.createConsumer(destination); consumer.setMessageListener(this); // Producer destHouseKeeping = pSession.createQueue(QUEUE_ID); producer = pSession.createProducer(null); producer.setDeliveryMode(DeliveryMode.PERSISTENT); connection.start(); // Database prep work try { // Look for our table checkTable(NOTIFICATIONS_TABLE); // Sync in-memory actions to database syncActionList(); // Purge any old 'block' entries since we just (re)started for (UserAction ua : actions) { if (ua.block) { removeAction(ua.id); } } } catch (SQLException ex) { log.error("Error during database preparation:", ex); } log.debug("Derby house keeping database online!"); // Quartz Scheduler try { scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); quartzScheduling(); } catch (SchedulerException ex) { log.error("Scheduled failed to start: ", ex); } // Start our callback timer log.info("Starting callback timer. Timeout = {}s", timeout); timer = new Timer("HouseKeeping", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { onTimeout(); } }, 0, timeout * 1000); } catch (IOException ex) { log.error("Unable to read config!", ex); } catch (JMSException ex) { log.error("Error starting message thread!", ex); } closeLog(); }
From source file:com.example.ecgfile.DeviceControlActivity.java
public void RTUploadTask() { if (mTimer2 == null) { mTimer2 = new Timer(); }/*from www .ja v a2s . c om*/ mTimerTask2 = new TimerTask() { @Override public void run() { if (!isRealTimeUp || !mButton_remoteUpload_enable.isChecked()) { cleanRTUploadTask(); } // getFile(CommonVar.ecgFilePathTemp); // if (files.size() >= 1) { new postFiles().execute(); } } }; mTimer2.schedule(mTimerTask2, 15 * 1000, 8 * 1000); //158 }
From source file:io.kristal.locationplugin.LocationPlugin.java
private void startLocationUpdates() { mBestLocation = null;//from w w w . ja v a2 s . c o m for (String provider : mProviders) { Location location = mLocationManager.getLastKnownLocation(provider); if (location != null) { if (isBetterLocation(location)) { mBestLocation = location; } if (MODE_ALL.equals(mMode)) { sendLocation(location); } else if (location.getAccuracy() < mAccuracy && location.getTime() > (new Date().getTime() - mTimestamp)) { sendLocation(location); return; } } } for (String provider : mProviders) { // TODO: see if another method is more convenient mLocationManager.requestLocationUpdates(provider, mFrequency, 0, this); } if (mTimeout > 0) { mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { mLocationManager.removeUpdates(LocationPlugin.this); sendStatus(STATUS_TIMEOUT); } }, mTimeout); } }
From source file:burstcoin.jminer.core.network.Network.java
public void startMining() { timer.schedule(new TimerTask() { @Override/*www .j a v a2 s .c om*/ public void run() { checkNetworkState(); } }, 100, CoreProperties.getRefreshInterval()); // on solo mining if (!CoreProperties.isPoolMining()) { timer.schedule(new TimerTask() { @Override public void run() { triggerServer(); } }, 5000, 25000); } }
From source file:svc.managers.SMSManager.java
private String generateViewCitationsAgainMessage(HttpSession session, HttpServletRequest request, String menuChoice) {//from w ww. j av a 2 s .co m String message = ""; String citationNumber = (String) session.getAttribute("citationNumber"); String courtDateTime = (String) session.getAttribute("courtDateTime"); String phoneNumber = (String) session.getAttribute("phoneNumber"); String dob = (String) session.getAttribute("dob"); switch (menuChoice) { case "1": message = generateReadLicenseMessage(session); break; case "2": message = "Visit "; message += clientURL + "/citations"; message += "/" + citationNumber; message += replyWithAdditionalViewingOptions(); setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN); break; case "3": if (smsAlertManager.add(citationNumber, LocalDateTime.parse(courtDateTime), phoneNumber, DatabaseUtilities.convertUSStringDateToLD(dob))) { //if a demo citation was created automatically send out an sms alert in 1 minute. if (citationNumber.startsWith("STLC")) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { smsNotifier.sendAlerts(citationNumber, phoneNumber); smsAlertManager.remove(citationNumber, phoneNumber, DatabaseUtilities.convertUSStringDateToLD(dob)); } }, 1 * 60 * 1000); } message = "You will receive 3 text message reminders about your court date. The first one will be sent two weeks prior to your court date. The second will be send one week prior and the final one will be sent the day before your court date."; message += "\n\n For help, respond HELP, to stop, respond STOP"; message += "\n\n Responding with STOP will prevent you from receiving any reminders now and in the future as well as using any part of this SMS service. If you'd like to cancel your reminder, you can cancel using the same text message menu you used to sign up."; message += "\n\n" + replyWithAdditionalViewingOptionsNoText(); setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN); } else { message = "Sorry, something went wrong in processing your request for text message reminders."; setNextStageInSession(session, SMS_STAGE.WELCOME); } break; case "4": if (smsAlertManager.remove(citationNumber, phoneNumber, DatabaseUtilities.convertUSStringDateToLD(dob))) { message = "You have been removed from receiving text message reminders about this court date. If there are other court dates you have signed up to receive text message reminders for and you would like to be removed from receiving updates about those dates, please look them up by your citation number and remove them too."; message += replyWithAdditionalViewingOptionsNoText(); setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN); } else { message = "Sorry, something went wrong in processing your request to be removed from text message reminders."; setNextStageInSession(session, SMS_STAGE.WELCOME); } break; default: message = "Option not recognized."; message += replyWithAdditionalViewingOptions(); setNextStageInSession(session, SMS_STAGE.READ_MENU_CHOICE_VIEW_CITATIONS_AGAIN); break; } return message; }
From source file:org.frontcache.FrontCacheEngine.java
private void initialize() { logger = LoggerFactory.getLogger(FrontCacheEngine.class); loadDomainConfigs();//from w ww. j av a2 s .c om frontcacheHttpPort = FCConfig.getProperty("front-cache.http-port", "80"); frontcacheHttpsPort = FCConfig.getProperty("front-cache.https-port", "443"); fcHostId = FCConfig.getProperty(FCConfig.FRONTCACHE_ID_KEY); if (null == fcHostId) fcHostId = DEFAULT_FRONTCACHE_HOST_NAME_VALUE; logToHeadersConfig = "true".equals(FCConfig.getProperty("front-cache.log-to-headers", "false")) ? true : false; cacheProcessor = CacheManager.getInstance(); includeProcessor = IncludeProcessorManager.getInstance(); this.httpClient = newClient(); connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { if (connectionManager == null) { return; } connectionManager.closeExpiredConnections(); } }, 30000, 5000); // log connectionManager stats connectionManagerTimer.schedule(new TimerTask() { @Override public void run() { if (connectionManager == null) { return; } PoolStats poolStats = connectionManager.getTotalStats(); logger.debug("HTTP connection manager pool stats - " + poolStats); // System.out.println("pool stats \n " + poolStats); } }, 1000, 60000); Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(3000); // wait server is started to load fallbacks from URLs } catch (Exception e) { e.printStackTrace(); } FallbackResolverFactory.init(httpClient); } }); t.start(); return; }
From source file:zjut.soft.finalwork.ui.SlidingActivity.java
private void timeSchedule() { // //from w w w . j av a 2 s . c o m // 1015 // Asp.net session 20 timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println(""); String result = new YCStudentManager().login(getApplicationContext(), app.get("selectedIp").toString(), app.get("username").toString(), app.get("password").toString()); System.out.println(result); } }, 10 * 60 * 1000, 15 * 60 * 1000); }