List of usage examples for java.util TimerTask TimerTask
protected TimerTask()
From source file:kr.co.generic.wifianalyzer.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { MainContext mainContext = MainContext.INSTANCE; mainContext.initialize(this, isLargeScreenLayout()); Settings settings = mainContext.getSettings(); settings.initializeDefaultValues();/*from w w w . ja va2 s. c om*/ setCurrentThemeStyle(settings.getThemeStyle()); setCurrentAccessPointView(settings.getAccessPointView()); setTheme(getCurrentThemeStyle().themeAppCompatStyle()); setWiFiChannelPairs(); super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); settings.registerOnSharedPreferenceChangeListener(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setOnClickListener(new WiFiBandToggle()); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); startNavigationMenu = settings.getStartMenu(); navigationMenuView = new NavigationMenuView(this, startNavigationMenu); onNavigationItemSelected(navigationMenuView.getCurrentMenuItem()); connectionView = new ConnectionView(this); Scanner scanner = mainContext.getScanner(); scanner.register(connectionView); HoonProperty.DevicesUUID = Utils.GetDevicesUUID(getApplicationContext()); HoonProperty.AppNM = "WiFi"; AdRequest adRequest = new AdRequest.Builder().build(); adView = (AdView) findViewById(R.id.adView); adView.loadAd(adRequest); TimerTask ts = new TimerTask() { @Override public void run() { MainActivity.this.runOnUiThread(new Runnable() { public void run() { if (um != null) um.cancel(true); um = new UserMonitor(); um.init("user", "", "", HoonProperty.bActive); um.execute(); } }); } }; Timer tm = new Timer(); // tm.scheduleAtFixedRate(ts, 0, 1000 * 30); tm.scheduleAtFixedRate(ts, 0, 1000 * 60); }
From source file:deincraftlauncher.IO.download.FTPDownloader.java
@Override public void start() { if (!prepared) { prepare();/*from w w w .j a v a 2 s .co m*/ } if (preparing) { try { prepareThread.join(); } catch (InterruptedException ex) { Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex); } } if (started) { return; } started = true; System.out.println("starting ftp download: " + fileName); finished = false; updateNum = 0; downloadThread = new Thread() { @Override public void run() { System.out.println("FTPDownload Thread started"); File targetPath = new File(saveTo); if (!targetPath.exists()) { targetPath.mkdirs(); } saveTo += fileName; System.out.println("Starting Download; Link=" + link + " saveTo=" + saveTo); //Actual download code try { OutputStream output = new FileOutputStream(saveTo); CountingOutputStream cos = new CountingOutputStream(output) { boolean updateReady = true; @Override protected void beforeWrite(int n) { super.beforeWrite(n); if (!updateReady) { return; } totalProgress = this.getCount() / totalSize; Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { updateReady = true; } }, updateDelay); updateReady = false; } }; update(); FTPConnection.getClient().retrieveFile(ftpfile.getName(), cos); cos.close(); output.close(); onFinished.call(instance); onFinishedB.call(instance); finished = true; System.out.println("Download fertig"); started = false; //download fertig downloadThread.interrupt(); } catch (IOException ex) { System.err.println("error while downliading via ftp: " + ex); } } }; downloadThread.start(); started = false; }
From source file:com.necla.simba.server.gateway.Main.java
public void serve() { try {/*from ww w .j av a 2 s .co m*/ stats = new StatsCollector(); stats.start("gateway.out"); boolean frontendCompression = Boolean .parseBoolean(properties.getProperty("frontend.compression", "true")); FrontendFrameEncoder.DOCOMPRESS = frontendCompression; String nodes = properties.getProperty("simbastores"); List<String> nodeArr = Arrays.asList(nodes.split("\\s*,\\s*")); backend = new BackendConnector(stats); subscriptionManager = new SubscriptionManager(backend); SeqNumManager sequencer = new SeqNumManager(); final NotificationManager nom = new NotificationManager(sequencer); cam = new ClientAuthenticationManager(subscriptionManager, nom, backend, sequencer); subscriptionManager.setClientAuthenticationManager(cam); // dump all notification info Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { // LOG.debug("Flushing print buffer..."); nom.dump(); subscriptionManager.dump(); } }, 0, 30000); StatsDumper dumper = new StatsDumper(); dumper.start(); backend.connect(properties, nodeArr, subscriptionManager, cam); FrontendServer frontend = new FrontendServer(properties, backend, stats, subscriptionManager, cam); LOG.debug("Gateway start-up complete."); } catch (IOException e) { LOG.error("Could not start server " + e.getMessage()); System.exit(1); } catch (URISyntaxException e) { LOG.error("Invalid host specification: " + e.getMessage()); System.exit(1); } catch (Exception e) { LOG.error("Could not start server " + e.getMessage()); e.printStackTrace(); } }
From source file:asia.stampy.server.listener.subscription.AbstractAcknowledgementListenerAndInterceptor.java
private void startTimerTask(final HostPort hostPort, final String ack) { TimerTask task = new TimerTask() { @Override//w w w . j a va 2 s . c o m public void run() { Queue<String> q = messages.get(hostPort); if (q == null || !q.contains(ack)) return; getHandler().noAcknowledgementReceived(ack); q.remove(ack); } }; ackTimer.schedule(task, getAckTimeoutMillis()); }
From source file:it_minds.dk.eindberetningmobil_android.views.UploadingView.java
private void TrySendReport(final DriveReport toSend) { final Timer timer = new Timer(); ServerFactory.getInstance(this).sendReport(toSend, new ResultCallback<JSONObject>() { @Override/*w w w . j a v a 2 s.c o m*/ public void onSuccess(JSONObject result) { Log.d("RESULT", result.toString()); updateStatusText(getString(R.string.success)); spinner.setVisibility(View.INVISIBLE); MainSettings.getInstance(UploadingView.this).removeSavedReport(saveableReport); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { startActivity(new Intent(UploadingView.this, StartActivity.class)); finish(); } }); } }, WAIT_TIME_MS_SUCCESS_DISSAPEAR); } @Override public void onError(Exception error) { updateStatusText(getString(R.string.error)); Log.e("temp", "error", error); new ConfirmationDialog(UploadingView.this, getString(R.string.error_dialog_title), getString(R.string.send_report_error), getString(R.string.send_report_error_retry), getString(R.string.send_report_error_cancel), null, new ResultCallback<Boolean>() { @Override public void onSuccess(Boolean result) { TrySendReport(toSend); } @Override public void onError(Exception error) { startActivity(new Intent(UploadingView.this, StartActivity.class)); finish(); } }).showDialog(); } }); /* ServerFactory.getInstance(this).sendReport(toSend, new ResultCallback<UserInfo>() { @Override public void onSuccess(UserInfo result) { updateStatusText(getString(R.string.success)); spinner.setVisibility(View.INVISIBLE); MainSettings.getInstance(UploadingView.this).removeSavedReport(saveableReport); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { startActivity(new Intent(UploadingView.this, StartActivity.class)); finish(); } }); } }, WAIT_TIME_MS_SUCCESS_DISSAPEAR); } @Override public void onError(final Exception error) { updateStatusText(getString(R.string.error)); Log.e("temp", "error", error); new ConfirmationDialog(UploadingView.this, getString(R.string.error_dialog_title), getString(R.string.send_report_error), getString(R.string.send_report_error_retry), getString(R.string.send_report_error_cancel), null, new ResultCallback<Boolean>() { @Override public void onSuccess(Boolean result) { TrySendReport(toSend); } @Override public void onError(Exception error) { startActivity(new Intent(UploadingView.this, StartActivity.class)); finish(); } }).showDialog(); } }); */ }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowChartJDialog.java
/** Creates new form InvestmentFlowChartJDialog */ public InvestmentFlowChartJDialog(java.awt.Frame parent, boolean modal, PortfolioManagementJPanel portfolioManagementJPanel) { super(parent, modal); initComponents();/*from ww w . j a v a 2 s.c o m*/ // Initialize main data structures. this.portfolioManagementJPanel = portfolioManagementJPanel; initJComboBox(); // We need a stock price monitor, to update all the stocks value. initRealTimeStockMonitor(); final JFreeChart freeChart = createChart(); org.yccheok.jstock.charting.Utils.applyChartTheme(freeChart); this.chartPanel = new ChartPanel(freeChart, true, true, true, true, true); // Make chartPanel able to receive key event. // So that we may use arrow left/right key to move around yellow // information boxes. We may also use up/down key to perform combo box // selection. this.chartPanel.setFocusable(true); this.chartPanel.requestFocus(); this.layer = new org.jdesktop.jxlayer.JXLayer<ChartPanel>(this.chartPanel); this.investmentFlowLayerUI = new InvestmentFlowLayerUI<ChartPanel>(this); layer.setUI(this.investmentFlowLayerUI); getContentPane().add(layer, java.awt.BorderLayout.CENTER); loadDimension(); new Timer().schedule(new TimerTask() { @Override public void run() { // Timeout. Remove busy message box. finishLookUpPrice = true; investmentFlowLayerUI.setDirty(true); } }, 15000); // Handle zoom-in. addChangeListener(this.chartPanel); // Handle resize. this.addComponentListener(new java.awt.event.ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { // Sequence is important. We will use invest information box as master. // ROI information box will be adjusted accordingly. investmentFlowLayerUI.updateInvestPoint(); investmentFlowLayerUI.updateROIPoint(); } }); }
From source file:io.kamax.mxisd.invitation.InvitationManager.java
@PostConstruct private void postConstruct() { gson = new Gson(); log.info("Loading saved invites"); Collection<ThreePidInviteIO> ioList = storage.getInvites(); ioList.forEach(io -> {//from www .j a va2 s . c o m log.info("Processing invite {}", gson.toJson(io)); ThreePidInvite invite = new ThreePidInvite(new MatrixID(io.getSender()), io.getMedium(), io.getAddress(), io.getRoomId(), io.getProperties()); ThreePidInviteReply reply = new ThreePidInviteReply(getId(invite), invite, io.getToken(), ""); invitations.put(reply.getId(), reply); }); // FIXME export such madness into matrix-java-sdk with a nice wrapper to talk to a homeserver try { SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()) .build(); HostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); } catch (Exception e) { // FIXME do better... throw new RuntimeException(e); } log.info("Setting up invitation mapping refresh timer"); refreshTimer = new Timer(); refreshTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { lookupMappingsForInvites(); } catch (Throwable t) { log.error("Error when running background mapping refresh", t); } } }, 5000L, TimeUnit.MILLISECONDS.convert(cfg.getResolution().getTimer(), TimeUnit.MINUTES)); }
From source file:com.icesoft.applications.faces.auctionMonitor.beans.LogBean.java
/** * Method to silently reset the auction every night at midnight *///from ww w .j a va2 s .c o m private void timedReset() { // Generate the date for tomorrow at midnight Calendar tomorrow = new GregorianCalendar(); tomorrow.add(Calendar.DATE, 1); Date midnight = new GregorianCalendar(tomorrow.get(Calendar.YEAR), tomorrow.get(Calendar.MONTH), tomorrow.get(Calendar.DATE)).getTime(); // Setup the timer task object, or cancel existing tasks on the current object if (nightlyReset == null) { nightlyReset = new Timer("Nightly Auction Reset", true); } else { nightlyReset.cancel(); nightlyReset.purge(); } // Schedule a task to reset at midnight, then every 24 hours past that nightlyReset.scheduleAtFixedRate(new TimerTask() { public void run() { log.info("Nightly reset of auction items."); resetAuction(true); } }, midnight, TIME_DAYS); }
From source file:com.dsh105.nexus.command.module.github.GitHubKeyCommand.java
@Override public boolean onCommand(final CommandPerformEvent event) { if (event.getArgs().length == 0) { event.respond("Please follow the following instructions:", true); event.respond(//w w w . jav a 2s . c o m "- Visit " + URLShortener .shortenGit(AUTHORISE .replace("{client_id}", Nexus.getInstance().getGitHubConfig() .getGitHubOauthAppClientId()) .replace("{scope}", Nexus.getInstance().getGitHubConfig().getGitHubOauthAppScope()) .replace("{state}", Nexus.getInstance().getGitHubConfig() .getGitHubOauthAppState())), true); event.respond("- Allow Nexus access.", true); event.respond( "- Copy the URL you are redirected to (the code information in this is important, so don't change anything!).", true); event.respond("- Perform {0}, where <code> is the URL you copied above.", true, Nexus.getInstance().getConfig().getCommandPrefix() + this.info().command() + " <code>"); if (!event.isInPrivateMessage()) { event.respondWithPing( "Please check your private messages for instructions on how to configure your GitHub API key."); } return true; } else if (event.getArgs().length == 1) { // request confirmed - check if valid String codeUrl = event.getArgs()[0]; try { HashMap<String, String> params = getParams(codeUrl); String code = params.get("code"); String state = params.get("state"); if (code != null && state != null && state.equals(Nexus.getInstance().getGitHubConfig().getGitHubOauthAppState())) { HttpResponse<JsonNode> response = Unirest.get(ACCESS_TOKEN .replace("{client_id}", Nexus.getInstance().getGitHubConfig().getGitHubOauthAppClientId()) .replace("{client_secret}", Nexus.getInstance().getGitHubConfig().getGitHubOauthAppClientSecret()) .replace("{code}", code)).header("accept", "application/json").asJson(); try { final String accessToken = response.getBody().getObject().getString("access_token"); final String nick = event.getSender().getNick(); Nexus.getInstance().sendIRC().message("NickServ", "info " + nick); new Timer().schedule(new TimerTask() { @Override public void run() { String account = Nexus.getInstance().getNicksConfig().getAccountNameFor(nick); if (account != null && !account.isEmpty()) { Nexus.getInstance().getGitHubConfig().set("github-key-" + account, accessToken); Nexus.getInstance().getGitHubConfig().save(); event.respondWithPing( "You may now use the Nexus commands requiring API key information (e.g. IRC notification settings)."); } else { event.errorWithPing( "Oh no! Something bad happened. I couldn't retrieve your API key from GitHub :("); } } }, 5000); return true; } catch (JSONException e) { event.errorWithPing("Access denied. Reason: \"{0}\"", response.getBody().getObject().getString("error_description")); return true; } } else { event.errorWithPing( "This code isn't right! Please make sure you copy the entire URL into the command."); return true; } } catch (UnirestException e) { throw new GenericUrlConnectionException("Failed to connect.", e); } catch (MalformedURLException e) { event.errorWithPing( "Invalid URL code provided. Please make sure you copy the entire URL into the command."); return true; } } return false; }
From source file:gov.nih.nci.caxchange.messaging.RegistrationLoadTest.java
private TimerTask getTimerTask(final int sfx) { return new TimerTask() { @Override/*from www . ja va 2 s.c o m*/ public void run() { es.execute(getRunnable(sfx)); } }; }