List of usage examples for java.util Timer Timer
public Timer()
From source file:io.kristal.locationplugin.LocationPlugin.java
private void startLocationUpdates() { mBestLocation = null;//from w w w. j a v a2 s . c om 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:svc.managers.SMSManager.java
private String generateViewCitationsAgainMessage(HttpSession session, HttpServletRequest request, String menuChoice) {/* w ww . j a va 2 s.c o 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:zjut.soft.finalwork.ui.SlidingActivity.java
private void timeSchedule() { // //from ww w. j a v a2 s . co 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); }
From source file:com.trsst.server.TrsstAdapter.java
/** * Called to trigger an asynchronous fetch, usually after we have returned * possibly stale data and we want to make sure it's refreshed on the next * pull. This implementation uses a short fuse timer task queue, but others * should implement a heuristic to queue this task for later based on the * likelihood that a refetch is needed, e.g. factoring in time since last * update and frequency of updates, etc. *///w w w . jav a 2 s .co m protected void pullLaterFromRelay(final String feedId, final RequestContext request) { if (TASK_QUEUE == null) { TASK_QUEUE = new Timer(); } final String uri = request.getResolvedUri().toString(); log.debug("fetchLaterFromRelay: queuing: " + uri); if (!COALESCING_TIMERS.containsKey(uri)) { log.debug("fetchLaterFromRelay: creating: " + uri); TimerTask task = new TimerTask() { public void run() { log.debug("fetchLaterFromRelay: starting: " + uri); pullFromRelay(feedId, request); COALESCING_TIMERS.remove(uri); } }; COALESCING_TIMERS.put(uri, task); TASK_QUEUE.schedule(task, 6000); // six seconds } }
From source file:com.data.pack.ViewVideo.java
@Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.videoplay);//from ww w .j a v a2 s . c o m Intent i = getIntent(); Bundle extras = i.getExtras(); filename = extras.getString("workoutname"); workoutID = extras.getString("workoutID"); UserName = extras.getString("UserName"); userID = extras.getString("userID"); // l= (View)findViewById(R.id.btnnavigation); btnQuit = (Button) findViewById(R.id.headeQuitricon); // btnplay =(Button)findViewById(R.id.btnplay); placeData = new PlaceDataSQL(this); GlobalData.appcount++; if (arrVoVideoName == null) arrVoVideoName = new ArrayList<VOWorkoutVideos>(); GlobalData.viewvideochange = 0; if (videoPathes == null) videoPathes = new ArrayList<Object>(); WindowManager.LayoutParams params = getWindow().getAttributes(); params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON; // params.screenBrightness = 10; getWindow().setAttributes(params); if (obUser.getSelectedLanguage().equals("1")) { YesString = "Yes"; strLeaveVideo = "You are about to exit the Video. Are you sure ?"; NoString = "No"; } else { YesString = "Ja"; QuitString = "verlassen"; strLeaveVideo = "Du bist dabei das Video zu beenden, bist Du sicher ?"; NoString = "Nein"; } count = 1; // Toast.makeText(getBaseContext(), "countcountcountcount" // +count,Toast.LENGTH_LONG).show(); // btnQuit =(Button) findViewById(R.id.headeQuitricon); btnQuit.setText(QuitString); btnQuit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // Intent intent = new Intent(sharescreen.this, // HomeScreen.class); // // intent.putExtra("userID", userID); // startActivity(intent); AlertDialog alertDialog = new AlertDialog.Builder(ViewVideo.this).create(); if (mVideoView.isPlaying()) { mVideoView.pause(); } alertDialog.setTitle("fitness4.me"); alertDialog.setMessage(strLeaveVideo); alertDialog.setButton(-1, YesString, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { GlobalData.viewvideochange = 1; Intent intent = new Intent(ViewVideo.this, FitnessforMeActivity.class); startActivity(intent); if (mVideoView != null) mVideoView.stopPlayback(); } catch (Exception e) { // TODO: handle exception } } }); alertDialog.setButton(-2, NoString, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { GlobalData.viewvideochange = 0; mVideoView.start(); dialog.cancel(); } }); try { alertDialog.show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); mycontroller = new MediaController(this); mVideoView = (VideoView) findViewById(R.id.surface_view); mVideoView.setMediaController(null); AdView adView = (AdView) this.findViewById(R.id.adView); if (GlobalData.allPurchased == true) { adView.setVisibility(View.GONE); } else { adView.setVisibility(View.VISIBLE); adView.loadAd(new AdRequest()); } try { myTimer = new Timer(); myTimer.schedule(new TimerTask() { @Override public void run() { TimerMethod(); } }, 1, 1000); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } mVideoView.setOnCompletionListener(myVideoViewCompletionListener); getDataAndPopulate(); }
From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java
public Set<SuggestionResult> searchMSD(String transWord, int maxCost, float insertionCost, float substitutionCost, float omissionCost, Distance distance) { // build first row List<Float> row = range(transWord.length() + 1); // results// ww w . j a v a 2s . co m Set<SuggestionResult> results = new HashSet<SuggestionResult>(); // iteratively (to prevent stack overflow) search each branch of the graph // a stack of paths to traverse. This prevents the StackOverflowException. Stack<StackLevenshteinEntry> stack = new Stack<StackLevenshteinEntry>(); for (Iterator<Long> iter = childIterator(nodes[0]); iter.hasNext();) { long child = iter.next(); char c = getChar(child); StackLevenshteinEntry entry = new StackLevenshteinEntry(child, transWord.toUpperCase().toCharArray(), String.valueOf(c), row); stack.push(entry); } // thread to control time to search for suggestions mAreTimeAvailable = true; mTimerTask = new TimerTask() { @Override public void run() { //Log.v(BrailleSpellCheckerService.TAG, "Search Interrupted!"); mAreTimeAvailable = false; } }; mTimer = new Timer(); mTimer.schedule(mTimerTask, 500); //500 ms to find all suggestions while (!stack.empty() && mAreTimeAvailable) { StackLevenshteinEntry entry = stack.pop(); List<Float> previousRow = entry.previousRow; int columns = entry.chars.length + 1; List<Float> currentRow = new LinkedList<Float>(); currentRow.add(previousRow.get(0) + omissionCost); // build one row for the letter, with a column for each letter in the target word, // plus one for the empty string at column 0 for (int column = 1; column < columns; column++) { // cost * braille_distance float insertCost = currentRow.get(column - 1) + insertionCost;// * //getInsertionDistance(entry.chars, column-1, getChar(entry.node)); float omitCost = previousRow.get(column) + omissionCost; float substituteCost = previousRow.get(column - 1); if (entry.chars[column - 1] != getChar(entry.node)) substituteCost += substitutionCost * distance.getDistance(entry.chars[column - 1], getChar(entry.node)); currentRow.add(Math.min(insertCost, Math.min(omitCost, substituteCost))); } // if last entry in the row indicates the optimal cost is less than the maximum cost, // and there is a word in this node, then add it. int last = currentRow.size() - 1; if (currentRow.get(last) <= maxCost && canTerminate(entry.node)) { results.add(new SuggestionResult(entry.subword, currentRow.get(last))); } // if any entries in the row are less than the maximum cost, then iteratively search each branch if (min(currentRow) <= maxCost) { for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) { // get child long child = iter.next(); // build subword StackLevenshteinEntry nextEntry = new StackLevenshteinEntry(child, entry.chars, entry.subword + getChar(child), currentRow); // search that branch stack.push(nextEntry); } } } mTimer.cancel(); // return list of results return results; }
From source file:de.yaacc.upnp.server.YaaccUpnpServerService.java
/** * // w w w . ja va2 s . c o m */ private void initialize() { this.initialized = false; if (!getUpnpClient().isInitialized()) { getUpnpClient().initialize(getApplicationContext()); watchdog = false; new Timer().schedule(new TimerTask() { @Override public void run() { watchdog = true; } }, 30000L); // 30 sec. watchdog while (!getUpnpClient().isInitialized() && !watchdog) { // wait for upnpClient initialization } } if (getUpnpClient().isInitialized()) { if (preferences.getBoolean( getApplicationContext().getString(R.string.settings_local_server_provider_chkbx), false)) { if (localServer == null) { localServer = createMediaServerDevice(); } getUpnpClient().getRegistry().addDevice(localServer); createHttpServer(); } if (preferences.getBoolean( getApplicationContext().getString(R.string.settings_local_server_receiver_chkbx), false)) { if (localRenderer == null) { localRenderer = createMediaRendererDevice(); } getUpnpClient().getRegistry().addDevice(localRenderer); } this.initialized = true; } else { throw new IllegalStateException("UpnpClient is not initialized!"); } startUpnpAliveNotifications(); }
From source file:com.piggate.samples.PiggateLoginService.Activity_Logged.java
@Override protected void onResume() { super.onResume(); handledClick = false;// www . ja v a 2 s. c o m timer = new Timer(); timer2 = new Timer(); timer.schedule(new TimerTask() { //Load offers data from the server using a request @Override public void run() { _piggate.refreshOffers(); //Refresh the offers for every Beacon calling the server every "timer" seconds } }, 0, 10000); timer2.schedule(new TimerTask() { //The offers were shown by timer callback @Override public void run() { showUINotification(_piggate.getOffers()); //Show notifications where are offers nearby } }, 0, 15000); }
From source file:be.fgov.kszbcss.rhq.websphere.config.cache.ConfigQueryCache.java
public void start(int numThreads) { synchronized (cache) { if (threads != null || stopping) { // start has already been called before throw new IllegalStateException(); }/*from w ww .ja v a 2s .c o m*/ if (persistentFile.exists()) { if (log.isDebugEnabled()) { log.debug("Reading persistent cache " + persistentFile); } try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(persistentFile)); try { for (int i = in.readInt(); i > 0; i--) { ConfigQueryCacheEntry<?> entry = (ConfigQueryCacheEntry<?>) in.readObject(); cache.put(entry.query, entry); } } finally { in.close(); } } catch (IOException ex) { log.error("Failed to read persistent cache data", ex); } catch (ClassNotFoundException ex) { log.error("Unexpected exception", ex); } } } if (log.isDebugEnabled()) { log.debug("Starting " + numThreads + " worker threads"); } threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { Thread thread = new Thread(this, name + "-query-" + (i + 1)); threads[i] = thread; thread.start(); } timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { persist(); } }, 5 * 60 * 1000); // TODO: need another timer that removes entries that are no longer used! }
From source file:com.piggate.samples.PiggateLogin.Activity_Logged.java
@Override protected void onResume() { super.onResume(); handledClick = false;//from ww w . ja va 2 s.c o m timer = new Timer(); timer2 = new Timer(); timer.schedule(new TimerTask() { //Load offers data from the server using a request @Override public void run() { _piggate.refreshOffers(); } }, 0, 3000); timer2.schedule(new TimerTask() { //The offers were shown by timer callback @Override public void run() { showUINotification(_piggate.getOffers()); //Show notifications where are offers nearby } }, 0, 15000); }