List of usage examples for java.util TimerTask TimerTask
protected TimerTask()
From source file:com.mibr.android.intelligentreminder.INeedToo.java
public void transmitNetwork(String thePhoneID) { if (thePhoneID.trim().toLowerCase().equals(this.getPhoneId().toLowerCase().trim())) { getLocationsTimer().schedule(new TimerTask() { public void run() { Thread notifyingThread = new Thread(null, mTaskTransmitNetwork, "TransmittingNetwork"); notifyingThread.setPriority(Thread.MIN_PRIORITY); notifyingThread.start(); }//from w ww. j a v a2 s .c om }, 1000 * 60 * 2); } }
From source file:com.com.easemob.chatuidemo.adapter.MessageAdapter.java
/** * ?// w w w. j a va 2s. co m * * @param message * @param holder * @param position * @param convertView */ private void handleFileMessage(final EMMessage message, final ViewHolder holder, int position, View convertView) { final NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody(); final String filePath = fileMessageBody.getLocalUrl(); holder.tv_file_name.setText(fileMessageBody.getFileName()); holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize())); holder.ll_container.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { File file = new File(filePath); if (file != null && file.exists()) { // FileUtils.openFile(file, (Activity) context); } else { // context.startActivity( new Intent(context, ShowNormalFileActivity.class).putExtra("msgbody", fileMessageBody)); } if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked && message.getChatType() != ChatType.GroupChat && message.getChatType() != ChatType.ChatRoom) { try { EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId()); message.isAcked = true; } catch (EaseMobException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); String st1 = context.getResources().getString(R.string.Have_downloaded); String st2 = context.getResources().getString(R.string.Did_not_download); if (message.direct == EMMessage.Direct.RECEIVE) { // ? EMLog.d(TAG, "it is receive msg"); File file = new File(filePath); if (file != null && file.exists()) { holder.tv_file_download_state.setText(st1); } else { holder.tv_file_download_state.setText(st2); } return; } // until here, deal with send voice msg switch (message.status) { case SUCCESS: holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); holder.staus_iv.setVisibility(View.INVISIBLE); break; case FAIL: holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); holder.staus_iv.setVisibility(View.VISIBLE); break; case INPROGRESS: if (timers.containsKey(message.getMsgId())) return; // set a timer final Timer timer = new Timer(); timers.put(message.getMsgId(), timer); timer.schedule(new TimerTask() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { holder.pb.setVisibility(View.VISIBLE); holder.tv.setVisibility(View.VISIBLE); holder.tv.setText(message.progress + "%"); if (message.status == EMMessage.Status.SUCCESS) { holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); timer.cancel(); } else if (message.status == EMMessage.Status.FAIL) { holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); holder.staus_iv.setVisibility(View.VISIBLE); Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_LONG).show(); timer.cancel(); } } }); } }, 0, 500); break; default: // ??? sendMsgInBackground(message, holder); } }
From source file:com.lfv.lanzius.application.Controller.java
public synchronized void stop(boolean leaveChannels, boolean waitChannelsLeft) { try {//from w ww .j a v a 2s.com long t = System.currentTimeMillis(); while (!semStartFinished && (System.currentTimeMillis() < (t + TIMEOUT_STARTSTOP))) wait(100); } catch (InterruptedException ex) { } if (autoTesterEnabled && autoTester != null) { autoTester.stopTester(); } semChannelsLeft = true; if (state == CLIENT_STATE_STARTED) { log.info("Stopping session"); state = CLIENT_STATE_CONNECTED; // Stop all sounds playSound(SOUND_NONE); if (footSwitch != null) footSwitch.stop(); if (peripheralLink != null) peripheralLink.PostRadioSendStop(); if (view != null) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { view.setVisible(false); view.dispose(); } }); } if (leaveChannels && bundle != null && !Config.CLIENT_SERVERLESS) { // Leave all channels Collection<Integer> c = new LinkedList<Integer>(); Iterator<ClientChannel> iterc = bundle.getChannelCollection().iterator(); while (iterc.hasNext()) { ClientChannel channel = iterc.next(); c.add(new Integer(channel.getId())); } semChannelsLeft = c.isEmpty(); if (!semChannelsLeft) networkManager.sessionDisconnect(); } // Stop decoder and close channels Iterator<ItemDispatcher> iterd = packetReceiver.getDataPacketDispatcherCollection().iterator(); while (iterd.hasNext()) { AudioDecoder decoder = (AudioDecoder) iterd.next(); int channelId = decoder.getDecoderId(); packetReceiver.closeChannel(channelId); if (audioRecorder != null) { audioRecorder.stopRecording(channelId); } decoder.stopModule(); } // Stop encoders if (encoder != null) { encoder.stopModule(); } if (monitorEncoder != null) { monitorEncoder.stopModule(); } packetReceiver.removeDataPacketDispatchers(); volumeRadioList.clear(); decoderPhone = null; decoderForward = null; encoder = null; monitorEncoder = null; model = null; sleep(25); if (distributor != null) { distributor.removeAll(); distributor = null; } if (monitorDistributor != null) { monitorDistributor.removeAll(); monitorDistributor = null; } log.debug("Session stopped, Waiting for start session packet from server"); // The system is not allowed to be started immediately after stop if (timer != null) { semStopFinished = false; timer.schedule(new TimerTask() { public void run() { Controller c = Controller.getInstance(); synchronized (c) { semStopFinished = true; c.notifyAll(); } } }, DELAY_STARTSTOP); } if (leaveChannels && waitChannelsLeft && !semChannelsLeft && !Config.CLIENT_SERVERLESS) { try { long t = System.currentTimeMillis(); while (!semChannelsLeft && (System.currentTimeMillis() < (t + TIMEOUT_LEAVE))) wait(100); if (!semChannelsLeft) log.warn("Wait for channels left timed out!"); } catch (InterruptedException ex) { log.warn("Wait for channels left interrupted!"); } } } }
From source file:com.delphix.session.test.ServiceTest.java
@Test public void testSyncDispatchReset() { int numThreads = 8; // Configure the server Server server = serverManager.locate(delayService.getServiceName()); HelloDelayService delay = (HelloDelayService) server.getService(); delay.setDelay(1000);/* w ww. j a v a 2 s . co m*/ final Timer timer = new Timer(); server.addListener(new SessionEventListener(new SessionEventRunnable() { @Override public void work() { timer.schedule(new TimerTask() { @Override public void run() { nexus.close(); } }, 500); } })); // Create the session ClientConfig spec = initServiceSpec(new HelloDelayService(delayService)); // Set a small fore channel queue depth to test sync dispatch ServiceOptions proposal = spec.getOptions(); proposal.setOption(FORE_QUEUE_DEPTH, 2); proposal.setOption(SYNC_DISPATCH, true); ClientNexus client = clientManager.create(spec); login(client); // Issue commands over the fore channel issueCommands(client, numThreads, 4096, 0); // Wait for the test to complete awaitDone(numThreads + 1); timer.cancel(); }
From source file:com.shengtao.chat.chatUI.adapter.MessageAdapter.java
/** * ?//from w ww. j a va 2 s. c om * * @param message * @param holder * @param position * @param convertView */ private void handleFileMessage(final EMMessage message, final ViewHolder holder, int position, View convertView) { final NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody(); final String filePath = fileMessageBody.getLocalUrl(); holder.tv_file_name.setText(fileMessageBody.getFileName()); holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody.getFileSize())); holder.ll_container.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { File file = new File(filePath); if (file != null && file.exists()) { // FileUtils.openFile(file, (Activity) context); } else { // context.startActivity( new Intent(context, ShowNormalFileActivity.class).putExtra("msgbody", fileMessageBody)); } if (message.direct == Direct.RECEIVE && !message.isAcked && message.getChatType() != ChatType.GroupChat && message.getChatType() != ChatType.ChatRoom) { try { EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId()); message.isAcked = true; } catch (EaseMobException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); String st1 = context.getResources().getString(string.Have_downloaded); String st2 = context.getResources().getString(string.Did_not_download); if (message.direct == Direct.RECEIVE) { // ? EMLog.d(TAG, "it is receive msg"); File file = new File(filePath); if (file != null && file.exists()) { holder.tv_file_download_state.setText(st1); } else { holder.tv_file_download_state.setText(st2); } return; } // until here, deal with send voice msg switch (message.status) { case SUCCESS: holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); holder.staus_iv.setVisibility(View.INVISIBLE); break; case FAIL: holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); holder.staus_iv.setVisibility(View.VISIBLE); break; case INPROGRESS: if (timers.containsKey(message.getMsgId())) return; // set a timer final Timer timer = new Timer(); timers.put(message.getMsgId(), timer); timer.schedule(new TimerTask() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { holder.pb.setVisibility(View.VISIBLE); holder.tv.setVisibility(View.VISIBLE); holder.tv.setText(message.progress + "%"); if (message.status == EMMessage.Status.SUCCESS) { holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); timer.cancel(); } else if (message.status == EMMessage.Status.FAIL) { holder.pb.setVisibility(View.INVISIBLE); holder.tv.setVisibility(View.INVISIBLE); holder.staus_iv.setVisibility(View.VISIBLE); Toast.makeText(activity, activity.getString(string.send_fail) + activity.getString(string.connect_failuer_toast), 0).show(); timer.cancel(); } } }); } }, 0, 500); break; default: // ??? sendMsgInBackground(message, holder); } }
From source file:coffeshop.PaymentPage.java
private void btcTimer() { Timer timer = new Timer(); //new timer timeExpired = false;//from w w w. java 2 s.co m TimerTask task = new TimerTask() { int counter = 10; public void run() { int minutes = 0; int seconds = 0; minutes = counter / 60; seconds = counter % 60; if (timeStop) { timer.cancel(); timer.purge(); } else { String timeString = String.format("Time Left: %02d:%02d", minutes, seconds); lblTimer.setText(timeString); counter--; if (counter == -1) { timer.cancel(); timer.purge(); lblTimer.setText("Time Expired"); timeExpired = true; lblQRC.setIcon(defaultQR); } } } }; timer.scheduleAtFixedRate(task, 1000, 1000); }
From source file:dentex.youtube.downloader.DashboardActivity.java
@Override public void onResume() { super.onResume(); Utils.logger("v", "_onResume", DEBUG_TAG); isDashboardRunning = true;//from www . jav a2s .c om /* * Timer() adapted from Stack Overflow: * http://stackoverflow.com/questions/3701106/periodically-refresh-reload-activity * * Q: http://stackoverflow.com/users/446413/raffe * A: http://stackoverflow.com/users/244296/cristian */ autoUpdate = new Timer(); autoUpdate.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { int inProgressIndex = 0; for (int i = 0; i < statusEntries.size(); i++) { if (statusEntries.get(i).equals(YTD.JSON_DATA_STATUS_IN_PROGRESS)) { inProgressIndex++; } } if (inProgressIndex > 0) { //Utils.logger("v", "refreshing...", DEBUG_TAG); refreshlist(sDashboard); } } }); } }, 500, 500); }
From source file:com.irccloud.android.NetworkConnection.java
public void schedule_idle_timer() { if (idleTimerTask != null) idleTimerTask.cancel();//from w ww .j av a2 s .c o m if (idle_interval <= 0) return; try { idleTimerTask = new TimerTask() { public void run() { if (handlers.size() > 0) { Crashlytics.log(Log.INFO, TAG, "Websocket idle time exceeded, reconnecting..."); state = STATE_DISCONNECTING; notifyHandlers(EVENT_CONNECTIVITY, null); if (client != null) client.disconnect(); connect(session); } reconnect_timestamp = 0; } }; idleTimer.schedule(idleTimerTask, idle_interval); reconnect_timestamp = System.currentTimeMillis() + idle_interval; } catch (IllegalStateException e) { //It's possible for timer to get canceled by another thread before before it gets scheduled //so catch the exception } }
From source file:gtu._work.etc.EnglishTester.java
void startNow() { final StringBuilder currentTime = new StringBuilder(); currentTime.append(System.currentTimeMillis()); wordsList = new ArrayList<String>(); pickProp = new Properties(); if (picOnly.isSelected()) { filterHasPicProp();/*from w ww . ja v a 2 s .c om*/ } for (Enumeration<?> enu = englishProp.propertyNames(); enu.hasMoreElements();) { String key = (String) enu.nextElement(); String value = englishProp.getProperty(key); wordsList.add(key); } wordsList = RandomUtil.randomList(wordsList); if (sortChkBox.isSelected()) { Collections.sort(wordsList); ifIsNumberSort(wordsList); } propCountLabel.setText(String.valueOf(englishProp.size())); questionCountLabel.setText(String.valueOf(wordsList.size())); // ? inputTestTrainer.initQuestion(); setVisible(false); final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // jTabbedPane1.setSelectedIndex(tabSelectedCombo.getSelectedIndex());// // if (!EnglishTester.gtu.swing.util.JFrameUtil.isVisible(this)) { setVisible(true); } // ?? if (currentWordIndex == wordsList.get(0)) { return; } // System.out.println(wordsList); if (!wordsList.isEmpty()) { String word = wordsList.get(0); // setCurrentWord(word); // scanPic(); if (showChineseOption.isSelected()) { setPictureDialogShow(true); } // resetAnswers(word); // } else { JCommonUtil._jOptionPane_showMessageDialog_info("words is over"); timer.cancel(); } } }, 0, DELAY_TIME); }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private void deleteOutdatedMessages(String paxosID, int version, Ballot ballot, int slot, int ballotnum, int coordinator, int acceptedGCSlot) { /* Delete logged messages from before the checkpoint. Note: Putting this * before cleanup(conn) above can cause deadlock if we don't have at * least 2x the number of connections as concurrently active paxosIDs. * Realized this the hard way. :) */ if (ENABLE_JOURNALING && PAUSABLE_INDEX_JOURNAL) this.messageLog.setGCSlot(paxosID, version, slot - acceptedGCSlot < 0 ? slot : acceptedGCSlot); else if (Util.oneIn(getLogGCFrequency()) && this.incrNumGCs() == 0) { Runnable gcTask = new TimerTask() { @Override/*from ww w . ja v a 2 s . c o m*/ public void run() { try { int priority = Thread.currentThread().getPriority(); Thread.currentThread().setPriority(Thread.MIN_PRIORITY); long t = System.currentTimeMillis(); SQLPaxosLogger.this.deleteOutdatedMessagesDB(paxosID, slot, ballot.ballotNumber, ballot.coordinatorID, acceptedGCSlot); Thread.currentThread().setPriority(priority); DelayProfiler.updateDelay("DBGC", t); } catch (Exception | Error e) { log.severe(this + " incurred exception " + e.getMessage()); e.printStackTrace(); } } }; if (getLogGCFrequency() == 0) { gcTask.run(); } else { this.GC.submit(gcTask, 0); } assert (this.decrNumGCs() == 1); } }