List of usage examples for java.util TimerTask TimerTask
protected TimerTask()
From source file:deincraftlauncher.IO.download.FTPDownloader.java
private void update() { System.out.println("downloader update #" + updateNum); updateNum++;/*from ww w .j av a 2 s . c om*/ if (finished) { System.out.println("cancelling updating"); return; } onUpdate.call(totalProgress, totalSize, this); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { //periodic update timer.cancel(); timer.purge(); update(); } }, updateDelay); }
From source file:de.uni_koeln.spinfo.maalr.webapp.controller.EditorController.java
@Override public String export(Set<String> fields, MaalrQuery query) throws Exception { File dir = new File("exports"); dir.mkdirs();/* w ww . java 2 s . c om*/ final File tmp = new File(dir, "export_" + UUID.randomUUID() + ".tsv.zip"); Timer timer = new Timer(); service.export(fields, query, tmp); timer.schedule(new TimerTask() { @Override public void run() { if (tmp.exists()) { System.out.println("Deleting file " + tmp); tmp.delete(); } } }, 60000 * 30); return tmp.getName(); }
From source file:it.unime.mobility4ckan.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); sharedPref = getSharedPreferences("sharedprefs", MODE_PRIVATE); locationText = (TextView) findViewById(R.id.txv_gps); countdownText = (TextView) findViewById(R.id.txv_countdown); datasetNameText = (TextView) findViewById(R.id.txv_dataset); listView = (ListView) findViewById(R.id.sensor_listview); countdown = SensorConfig.countDownTimer; apikey = sharedPref.getString("userAPIkey", ""); sendNowBtn = (Button) findViewById(R.id.btn_invia); sendNowBtn.setOnClickListener(new View.OnClickListener() { @Override//ww w .j av a 2 s.c o m public void onClick(View v) { sendTask(false); } }); checkPermissionControl(); sensorList = SensorConfig.sensorList; mySensor = new MySensor(this); for (int k = 0; k < sensorList.size(); k++) { mySensor.registerSensor(sensorList.get(k)); } if (!isDeviceOnline()) { final AlertDialog mDialog = new AlertDialog.Builder(this).setMessage(getString(R.string.sei_offline)) .setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).create(); mDialog.show(); return; } if (!isGPSEnable()) { final AlertDialog mDialog = new AlertDialog.Builder(this) .setMessage(getString(R.string.gps_disattivato)).setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).create(); mDialog.show(); return; } if (sharedPref.getString("datasetName", "").isEmpty()) { setDatasetName(); } else { datasetNameText.setText(sharedPref.getString("datasetName", "")); datasetName = sharedPref.getString("datasetName", ""); startTimer(); } Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { createListView(); } }); } }, 0, 3000); }
From source file:burstcoin.jminer.core.round.Round.java
@EventListener public void handleMessage(NetworkStateChangeEvent event) { if (blockNumber < event.getBlockNumber()) { long previousBlockNumber = blockNumber; this.blockNumber = event.getBlockNumber(); this.baseTarget = event.getBaseTarget(); this.targetDeadline = event.getTargetDeadline(); long lastBestCommittedDeadline = bestCommittedDeadline; plots = reader.getPlots();/* www .j a va2 s . c om*/ initNewRound(plots); // reconfigure checker checker.reconfigure(blockNumber, baseTarget, targetDeadline, event.getGenerationSignature()); // start reader int scoopNumber = calcScoopNumber(event.getBlockNumber(), event.getGenerationSignature()); reader.read(previousBlockNumber, blockNumber, scoopNumber, lastBestCommittedDeadline); // ui event fireEvent(new RoundStartedEvent(blockNumber, scoopNumber, plots.getSize(), targetDeadline, baseTarget)); timer.schedule(new TimerTask() { @Override public void run() { network.checkLastWinner(blockNumber); } }, 0); // deferred } }
From source file:ispok.pokerclock.TournamentController.java
public synchronized void start() { timerCounter = new TimerTask() { @Override/* ww w . ja va 2 s. c o m*/ public void run() { decTime(); } }; timer.scheduleAtFixedRate(timerCounter, 1000, 1000); }
From source file:com.breadwallet.tools.manager.CurrencyManager.java
private void initializeTimerTask() { timerTask = new TimerTask() { public void run() { //use a handler to run a toast that shows the current timestamp handler.post(new Runnable() { public void run() { new GetCurrenciesTask().execute(); }/*from ww w.j a v a 2 s . c o m*/ }); } }; }
From source file:org.ulyssis.ipp.control.CommandDispatcher.java
public void sendAsync(Command command, BiConsumer<Command, Result> callback) { TimerTask timerTask = new TimerTask() { public void run() { handleResult(command.getCommandId(), Result.TIMEOUT); }/*from w w w . j a v a 2s . co m*/ }; processingCommands.put(command.getCommandId(), new ProcessingCommand(command, callback, timerTask)); timeoutTimer.schedule(timerTask, 10000L); commandsToSend.add(command); }
From source file:com.linkedin.pinot.server.integration.realtime.RealtimeTableDataManagerTest.java
public void testSetup() throws Exception { final HLRealtimeSegmentDataManager manager = new HLRealtimeSegmentDataManager(realtimeSegmentZKMetadata, tableConfig, instanceZKMetadata, null, tableDataManagerConfig.getDataDir(), ReadMode.valueOf(tableDataManagerConfig.getReadMode()), getTestSchema(), new ServerMetrics(new MetricsRegistry())); final long start = System.currentTimeMillis(); TimerService.timer.scheduleAtFixedRate(new TimerTask() { @Override/*from w ww. j a va2s . c om*/ public void run() { if (System.currentTimeMillis() - start >= (SEGMENT_CONSUMING_TIME)) { keepOnRunning = false; } } }, 1000, 1000 * 60 * 1); TimerService.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { long start = System.currentTimeMillis(); long sum = 0; try { RealtimeSegment segment = (RealtimeSegment) manager.getSegment(); RealtimeColumnDataSource mDs = (RealtimeColumnDataSource) segment.getDataSource("count"); BlockValSet valSet = mDs.nextBlock().getBlockValueSet(); BlockSingleValIterator valIt = (BlockSingleValIterator) valSet.iterator(); int val = valIt.nextIntVal(); while (val != Constants.EOF) { val = valIt.nextIntVal(); sum += val; } } catch (Exception e) { LOGGER.info("count column exception"); e.printStackTrace(); } long stop = System.currentTimeMillis(); LOGGER.info("time to scan metric col count : " + (stop - start) + " sum : " + sum); } }, 20000, 1000 * 5); TimerService.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { long start = System.currentTimeMillis(); long sum = 0; try { RealtimeSegment segment = (RealtimeSegment) manager.getSegment(); RealtimeColumnDataSource mDs = (RealtimeColumnDataSource) segment.getDataSource("viewerId"); BlockValSet valSet = mDs.nextBlock().getBlockValueSet(); BlockSingleValIterator valIt = (BlockSingleValIterator) valSet.iterator(); int val = valIt.nextIntVal(); while (val != Constants.EOF) { val = valIt.nextIntVal(); sum += val; } } catch (Exception e) { LOGGER.info("viewerId column exception"); e.printStackTrace(); } long stop = System.currentTimeMillis(); LOGGER.info("time to scan SV dimension col viewerId : " + (stop - start) + " sum : " + sum); } }, 20000, 1000 * 5); TimerService.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { long start = System.currentTimeMillis(); long sum = 0; try { RealtimeSegment segment = (RealtimeSegment) manager.getSegment(); RealtimeColumnDataSource mDs = (RealtimeColumnDataSource) segment .getDataSource("daysSinceEpoch"); BlockValSet valSet = mDs.nextBlock().getBlockValueSet(); BlockSingleValIterator valIt = (BlockSingleValIterator) valSet.iterator(); int val = valIt.nextIntVal(); while (val != Constants.EOF) { val = valIt.nextIntVal(); sum += val; } } catch (Exception e) { LOGGER.info("daysSinceEpoch column exception"); e.printStackTrace(); } long stop = System.currentTimeMillis(); LOGGER.info("time to scan SV time col daysSinceEpoch : " + (stop - start) + " sum : " + sum); } }, 20000, 1000 * 5); TimerService.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { long start = System.currentTimeMillis(); long sum = 0; float sumOfLengths = 0F; float counter = 0F; try { RealtimeSegment segment = (RealtimeSegment) manager.getSegment(); RealtimeColumnDataSource mDs = (RealtimeColumnDataSource) segment .getDataSource("viewerCompanies"); Block b = mDs.nextBlock(); BlockValSet valSet = b.getBlockValueSet(); BlockMultiValIterator valIt = (BlockMultiValIterator) valSet.iterator(); BlockMetadata m = b.getMetadata(); int maxVams = m.getMaxNumberOfMultiValues(); while (valIt.hasNext()) { int[] vals = new int[maxVams]; int len = valIt.nextIntVal(vals); for (int i = 0; i < len; i++) { sum += vals[i]; } sumOfLengths += len; counter++; } } catch (Exception e) { LOGGER.info("daysSinceEpoch column exception"); e.printStackTrace(); } long stop = System.currentTimeMillis(); LOGGER.info("time to scan MV col viewerCompanies : " + (stop - start) + " sum : " + sum + " average len : " + (sumOfLengths / counter)); } }, 20000, 1000 * 5); while (keepOnRunning) { // Wait for keepOnRunning to be set to false } }
From source file:com.edduarte.protbox.core.registry.PReg.java
public void initialize() throws GeneralSecurityException, IOException { if (initialized) { return;/*from ww w.ja va2s . com*/ } // starts the cipher according to the chosen algorithm CIPHER = Cipher.getInstance(pair.getPairAlgorithm()); // starts the synchronization threads, who are responsible of syncing elements between the folders SyncModule.start(); // checks the registry periodically (every 2 seconds) and detects any changes made timerIndex = new Timer(); timerIndex.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { executeIntegrityCheck(); } catch (ProtboxException ex) { run(); } } }, 0, 5000); // starts the registry watchers for both prot and shared folders final Path sharedPath = Paths.get(pair.getSharedFolderPath()); final Path protPath = Paths.get(pair.getProtFolderPath()); sharedFolderWatcher = new DefaultWatcher(this, FolderOption.SHARED, sharedPath); protFolderWatcher = new DefaultWatcher(this, FolderOption.PROT, protPath); sharedFolderWatcher.start(); protFolderWatcher.start(); // starts a file watcher for creation of access request files requestFileWatcher = new RequestWatcher(sharedPath, detectedRequest -> { RequestPromptWindow.getInstance(this, detectedRequest); }); requestFileWatcher.start(); initialized = true; }
From source file:com.finlay.geomonsters.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { Log.v(TAG, "onCreated"); super.onCreate(savedInstanceState); _activity = this; // set app to fullscreen requestWindowFeature(Window.FEATURE_NO_TITLE); // layout/*from w ww .j av a 2 s. c om*/ setContentView(R.layout.activity_ranch); // Socket, Location Manager, Weather Manager locationListener = new MyLocationListener(this); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); socket = new SocketIO(); weatherManager = new WeatherManager(this); // layout items theTextView = (TextView) findViewById(R.id.txtMessage); forceButton = (Button) findViewById(R.id.btnGetLocation); waitButton = (Button) findViewById(R.id.btnWaitLocation); loadEncounterButton = (Button) findViewById(R.id.btnLoadEncounter); // TODO get rid of this. For now, reset the encounters file whenever created ConfigManager.ResetConfigFiles(getApplicationContext()); forceButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.v(TAG, "Force Click"); // Ensure connected if (!isNetworkAvailable()) { setMessage("No internet connection."); return; } forceButton.setText("..."); // Connect to server connectSocket(); // Best provider Criteria criteria = new Criteria(); String bestProvider = locationManager.getBestProvider(criteria, false); // Request location updates locationManager.requestLocationUpdates(bestProvider, 10000, 0, locationListener); forceButton.setEnabled(false); loadEncounterButton.setEnabled(false); } }); waitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.v(TAG, "Wait click"); waitButton.setText("..."); // Start Encounter Service // TODO Service should be started at boot? _activity.startService(new Intent(_activity, EncounterService.class)); waitButton.setEnabled(false); } }); loadEncounterButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Log.v(TAG, "Load encounter clicked"); // Ensure connection if (!isNetworkAvailable()) { setMessage("No internet connection."); return; } // Pull encounter String encounter = ConfigManager.PullEncounter(getApplicationContext()); if (encounter.equals("")) return; // Use location & time from gathered string to query encounter String[] location = encounter.split(","); String latitude = location[0]; String longitude = location[1]; // TODO We cannot get historical weatherdata accurately. So we will just use the current time :( // Pop used encounter from queue ConfigManager.PopEncounter(getApplicationContext()); // Server & weather connectSocket(); weatherManager.execute(longitude, latitude); while (!socket.isConnected()) ; // Send query to server sendLocation(longitude, latitude); } }); // Change the text value of the loadEncounterButton to the number of encounters available timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { loadEncounterButton.setText("" + ConfigManager.EncounterCount(getApplicationContext())); } }); } }, 0, UPDATE_DELAY); }