List of usage examples for java.util TimerTask TimerTask
protected TimerTask()
From source file:com.yahala.ui.LoginActivitySmsView.java
@Override public void setParams(Bundle params) { codeField.setText(""); OSUtilities.setWaitingForSms(true);//from w ww .j ava 2 s.c om NotificationCenter.getInstance().addObserver(this, 998); currentParams = params; waitingForSms = true; String phone = params.getString("phone"); requestPhone = params.getString("phoneFormated"); phoneHash = params.getString("phoneHash"); registered = params.getString("registered"); FileLog.e("yahala", requestPhone + " phoneHash:" + phoneHash + "registered" + params.getString("registered")); time = params.getInt("calltime"); String number = PhoneFormat.getInstance().format(phone); confirmTextView.setText(Html.fromHtml(String.format( ApplicationLoader.applicationContext.getResources().getString(R.string.SentSmsCode) + " <b>%s</b>", number))); OSUtilities.showKeyboard(codeField); codeField.requestFocus(); try { synchronized (timerSync) { if (timeTimer != null) { timeTimer.cancel(); timeTimer = null; } } } catch (Exception e) { FileLog.e("yahala", e); } timeText.setText(String.format("%s 1:00", ApplicationLoader.applicationContext.getResources().getString(R.string.CallText))); lastCurrentTime = System.currentTimeMillis(); timeTimer = new Timer(); timeTimer.schedule(new TimerTask() { @Override public void run() { double currentTime = System.currentTimeMillis(); double diff = currentTime - lastCurrentTime; time -= diff; lastCurrentTime = currentTime; Utilities.RunOnUIThread(new Runnable() { @Override public void run() { if (time >= 1000) { int minutes = time / 1000 / 60; int seconds = time / 1000 - minutes * 60; timeText.setText(String.format("%s %d:%02d", ApplicationLoader.applicationContext .getResources().getString(R.string.CallText), minutes, seconds)); } else { timeText.setText(ApplicationLoader.applicationContext.getResources() .getString(R.string.Calling)); synchronized (timerSync) { if (timeTimer != null) { timeTimer.cancel(); timeTimer = null; } } TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall(); req.phone_number = requestPhone; req.phone_code_hash = phoneHash; } } }); } }, 0, 1000); sendSmsRequest(); }
From source file:com.googlecode.fascinator.indexer.SolrWrapperQueueConsumer.java
/** * Start thread running/*from ww w.jav a 2 s. com*/ * */ @Override public void run() { try { MDC.put("name", name); log.info("Starting {}...", name); // 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(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = session.createConsumer(session.createQueue(QUEUE_ID)); consumer.setMessageListener(this); connection.start(); // Solr solr = initCore("solr"); // Timeout 'tick' for buffer (10s) timer = new Timer("SolrWrapper:" + toString(), true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkTimeout(); } }, 0, 10000); } catch (JMSException ex) { log.error("Error starting message thread!", ex); } }
From source file:cd.what.DutchBot.DutchBot.java
/** * Load the config files/*from w w w.j a v a2s . c om*/ * */ private void loadConfig() { if (this._config.containsKey("irc.nick") && !this.getNick().equals(this._config.getString("irc.nick", ""))) this.changeNick(this._config.getString("irc.nick")); if (this._config.containsKey("bot.globalmodules")) for (Object m : this._config.getList("bot.globalmodules").toArray()) { String module = m.toString().substring(0, 1).toUpperCase() + m.toString().substring(1) + "Module"; try { this.moduleManager.loadModule(module); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { this.logMessage("loading global module " + m + " failed", true); this.logMessage(e.getMessage(), true); e.printStackTrace(); } } if (this._config.containsKey("db.database") && this._config.containsKey("db.username") && this._config.containsKey("db.password")) DatabaseConnection.getInstance().connect(this._config.getString("db.host"), this._config.getString("db.database"), this._config.getString("db.username"), this._config.getString("db.password")); droneLogin(); TimerTask tt = new TimerTask() { @Override public void run() { sendRawLine("HS ON"); loadChannels(); } }; this.getTimer().schedule(tt, 3000); }
From source file:com.halseyburgund.rwframework.core.RWStreamAssetsTracker.java
/** * Starts tracking the assets streamed by the server. This basically * handles everything and does an intent broadcast when it estimates * the asset being played on the device is changed. I.e. it has passed * from the server stream and made it to the front of the audio buffer * on the device and the user started hearing it play. * /*from w ww.j ava2s .com*/ * The project configuration (will be retrieved from the RWService) is * used to get the streamMetadataEnabled property to decide if the * server will be sending metadata and using this class is possible. The * streamMetadataTimerIntervalMSec property specifies the timer interval * that will be used. * * The broadcasted intent has the following properties: * Action: RW.STREAM_METADATA_UPDATED * Extra : RW.EXTRA_STREAM_METADATA_CURRENT_ASSET_ID (int) * Extra : RW.EXTRA_STREAM_METADATA_PREVIOUS_ASSET_ID (int) * Extra : RW.EXTRA_STREAM_METADATA_TITLE (String) * * Call stop() when no longer interested in the metadata. This will * stop the tracking loop and free some resources. */ public void start() { if (mMetadataReaderTimer != null) { stop(); } RWConfiguration config = mRwService.getConfiguration(); if ((config != null) && (config.isStreamMetadataEnabled())) { if (D) { Log.d(TAG, "Starting stream metadata reader", null); } mMetadataReaderTimer = new Timer(); updateStreamMetadata(-1, ""); mMetadataReaderTimer.schedule(new TimerTask() { public void run() { streamMetadataUpdate(); } }, 0, config.getStreamMetadataTimerIntervalMSec()); } }
From source file:com.rogoman.easyauth.InMemoryUsedCodesManager.java
/** * Sets up the background thread to clean up the data structures periodically. *//*from w ww . ja va 2 s .c om*/ private void setupQueueCleanup() { timer.schedule(new TimerTask() { @Override public void run() { queueCleanup(); } }, cleanupTime, cleanupTime); }
From source file:esg.node.components.monitoring.ESGMonitor.java
private void startMonitoring() { log.trace("launching system monitor timer"); long delay = Long.parseLong(props.getProperty("monitor.initialDelay")); long period = Long.parseLong(props.getProperty("monitor.period")); log.trace("monitoring delay: " + delay + " sec"); log.trace("monitoring period: " + period + " sec"); Timer timer = new Timer(); timer.schedule(new TimerTask() { public final void run() { //log.trace("Checking for new node information... [busy? "+ESGMonitor.this.isBusy+"]"); if (!ESGMonitor.this.isBusy) { ESGMonitor.this.isBusy = true; if (fetchNodeInfo()) { //TODO monitorDAO.markLastCompletionTime(); }// w w w .jav a 2 s .com ESGMonitor.this.isBusy = false; } } }, delay * 1000, period * 1000); }
From source file:org.powertac.visualizer.services.VisualizerServiceTournament.java
/** * Called on initialization to start message feeder and state machine. *///from w w w .ja va 2s .co m public void init() { // Start the logger Logger root = Logger.getRootLogger(); root.removeAllAppenders(); try { PatternLayout logLayout = new PatternLayout("%r %-5p %c{2}: %m%n"); String logPath = System.getProperty("catalina.base", ""); if (!logPath.isEmpty()) { logPath += "/logs/" + machineName + "-viz.log"; } else { logPath += "log/" + machineName + "-viz.log"; } FileAppender logFile = new FileAppender(logLayout, logPath, false); root.addAppender(logFile); } catch (IOException ioe) { log.info("Can't open log file"); System.exit(0); } // Start the message feeder messageFeeder = new Thread(messagePump); messageFeeder.setDaemon(true); messageFeeder.start(); // Start the state machine tickTimer = new Timer(true); stateTask = new TimerTask() { @Override public void run() { log.debug("message count = " + visualizerBean.getMessageCount() + ", queue size = " + messageQueue.size()); // Timer fires every 30 secs, but tournamentLogin() sleep for 60 secs // if no game available. That would build up ticks in the queue if (currentState == loginWait && eventQueue.contains(Event.tick)) { return; } putEvent(Event.tick); } }; tickTimer.schedule(stateTask, 10, tickPeriod); stateRunner = new Thread(runStates); stateRunner.setDaemon(true); stateRunner.start(); }
From source file:org.sonews.daemon.sync.SynchronousNNTPConnection.java
private void shutdownOutput() { cancelTimer.schedule(new TimerTask() { @Override//w w w .java 2 s. co m public void run() { try { // Closes the output line of the channel's socket. channel.socket().shutdownOutput(); channel.close(); } catch (SocketException ex) { // Socket was already disconnected Log.get().log(Level.INFO, "NNTPConnection.shutdownOutput(): {0}", ex); } catch (IOException ex) { Log.get().log(Level.WARNING, "NNTPConnection.shutdownOutput(): {0}", ex); } } }, 3000); }
From source file:com.symbian.driver.plugins.comms.stat.StatProcess.java
/** * Starts a timer to terminate a job when the TimeOut has occured if Timeout * is greater than 0// ww w . j a v a 2 s. co m * * @param aTimeout * The length of time before the job should be canceled. * @return The Timer object which controls the timeout. */ private static Timer startTimer(final int aTimeout) { try { TIMEOUT_MAX = TDConfig.getInstance().getPreferenceInteger(TDConfig.TOTAL_TIMEOUT); } catch (ParseException lParseException) { // ignore , we have a default value. } Timer lTimeoutTimer = new Timer(false); lTimeoutTimer.schedule(new TimerTask() { public void run() { LOGGER.log(Level.SEVERE, "Time out : " + aTimeout + " ms reached."); STOP = true; } }, (aTimeout == 0) ? TIMEOUT_MAX : aTimeout); return lTimeoutTimer; }
From source file:net.frygo.findmybuddy.GCMIntentService.java
private static void generateAcceptfriendNotification(Context context, String message, String status) { Random rand = new Random(); int x = rand.nextInt(); NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, customlistview.class); if (status.equalsIgnoreCase("accept")) message = message + " added you as buddy"; else/*from w w w. j a va 2 s. c o m*/ message = message + " rejected you as buddy"; PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT); Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis()); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(x, notification); PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final PowerManager.WakeLock mWakelock = pm .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title); mWakelock.acquire(); // Timer before putting Android Device to sleep mode. Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { mWakelock.release(); } }; timer.schedule(task, 5000); }