List of usage examples for java.util Timer Timer
public Timer()
From source file:deincraftlauncher.IO.download.FTPDownloader.java
private void update() { System.out.println("downloader update #" + updateNum); updateNum++;// w w w. j a v a 2 s.c o m 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: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 a v a 2s . 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:com.taobao.common.tfs.DefaultTfsManager.java
private synchronized int doInit() { int ret = TfsConstant.TFS_SUCCESS; if (!enable) { if (runTimer && timer == null) { timer = new Timer(); timer.schedule((new GcWorker()), 0, ClientConfig.GC_INTERVAL); timer.schedule(tfsSession.getCacheMetric(), 0, ClientConfig.CACHEMETRIC_INTERVAL); }/*from www .jav a2 s . co m*/ if ((ret = tfsSession.init()) != TfsConstant.TFS_SUCCESS) { log.error("init tfs session fail, server: " + getNsip()); } else { enable = true; } } return ret; }
From source file:com.edduarte.protbox.core.registry.PReg.java
public void initialize() throws GeneralSecurityException, IOException { if (initialized) { return;// w w w . j a va 2 s . c o m } // 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:edu.uci.ics.jung.samples.AnimatingAddNodeDemo.java
@Override public void init() { //create a graph Graph<Number, Number> ig = Graphs .<Number, Number>synchronizedDirectedGraph(new DirectedSparseMultigraph<Number, Number>()); ObservableGraph<Number, Number> og = new ObservableGraph<Number, Number>(ig); og.addGraphEventListener(new GraphEventListener<Number, Number>() { public void handleGraphEvent(GraphEvent<Number, Number> evt) { System.err.println("got " + evt); }/* w w w . ja va 2s. c o m*/ }); this.g = og; //create a graphdraw layout = new FRLayout<Number, Number>(g); layout.setSize(new Dimension(600, 600)); Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); Layout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout); vv = new VisualizationViewer<Number, Number>(staticLayout, new Dimension(600, 600)); JRootPane rp = this.getRootPane(); rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE); getContentPane().setLayout(new BorderLayout()); getContentPane().setBackground(java.awt.Color.lightGray); getContentPane().setFont(new Font("Serif", Font.PLAIN, 12)); vv.setGraphMouse(new DefaultModalGraphMouse<Number, Number>()); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR); vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<Number>()); vv.setForeground(Color.white); vv.addComponentListener(new ComponentAdapter() { /** * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent) */ @Override public void componentResized(ComponentEvent arg0) { super.componentResized(arg0); System.err.println("resized"); layout.setSize(arg0.getComponent().getSize()); } }); getContentPane().add(vv); switchLayout = new JButton("Switch to SpringLayout"); switchLayout.addActionListener(new ActionListener() { @SuppressWarnings({ "unchecked", "rawtypes" }) public void actionPerformed(ActionEvent ae) { Dimension d = vv.getSize();//new Dimension(600,600); if (switchLayout.getText().indexOf("Spring") > 0) { switchLayout.setText("Switch to FRLayout"); layout = new SpringLayout<Number, Number>(g, new ConstantTransformer(EDGE_LENGTH)); layout.setSize(d); Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); StaticLayout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout); LayoutTransition<Number, Number> lt = new LayoutTransition<Number, Number>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } else { switchLayout.setText("Switch to SpringLayout"); layout = new FRLayout<Number, Number>(g, d); layout.setSize(d); Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); StaticLayout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout); LayoutTransition<Number, Number> lt = new LayoutTransition<Number, Number>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } } }); getContentPane().add(switchLayout, BorderLayout.SOUTH); timer = new Timer(); }
From source file:com.google.code.facebook.graph.sna.applet.AnimatingAddNodeDemo.java
@Override public void init() { //create a graph Graph<Number, Number> ig = Graphs .<Number, Number>synchronizedDirectedGraph(new DirectedSparseMultigraph<Number, Number>()); ObservableGraph<Number, Number> og = new ObservableGraph<Number, Number>(ig); og.addGraphEventListener(new GraphEventListener<Number, Number>() { public void handleGraphEvent(GraphEvent<Number, Number> evt) { System.err.println("got " + evt); }/*from ww w . j a va 2 s . co m*/ }); this.g = og; //create a graphdraw layout = new FRLayout<Number, Number>(g); layout.setSize(new Dimension(600, 600)); Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); Layout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout); vv = new VisualizationViewer<Number, Number>(staticLayout, new Dimension(600, 600)); JRootPane rp = this.getRootPane(); rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE); getContentPane().setLayout(new BorderLayout()); getContentPane().setBackground(java.awt.Color.lightGray); getContentPane().setFont(new Font("Serif", Font.PLAIN, 12)); vv.setGraphMouse(new DefaultModalGraphMouse<Number, Number>()); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR); vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<Number>()); vv.setForeground(Color.white); vv.addComponentListener(new ComponentAdapter() { /** * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent) */ @Override public void componentResized(ComponentEvent arg0) { super.componentResized(arg0); System.err.println("resized"); layout.setSize(arg0.getComponent().getSize()); } }); getContentPane().add(vv); switchLayout = new JButton("Switch to SpringLayout"); switchLayout.addActionListener(new ActionListener() { @SuppressWarnings("unchecked") public void actionPerformed(ActionEvent ae) { Dimension d = vv.getSize();//new Dimension(600,600); if (switchLayout.getText().indexOf("Spring") > 0) { switchLayout.setText("Switch to FRLayout"); layout = new SpringLayout<Number, Number>(g, new ConstantTransformer(EDGE_LENGTH)); layout.setSize(d); Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); StaticLayout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout); LayoutTransition<Number, Number> lt = new LayoutTransition<Number, Number>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } else { switchLayout.setText("Switch to SpringLayout"); layout = new FRLayout<Number, Number>(g, d); layout.setSize(d); Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); StaticLayout<Number, Number> staticLayout = new StaticLayout<Number, Number>(g, layout); LayoutTransition<Number, Number> lt = new LayoutTransition<Number, Number>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } } }); getContentPane().add(switchLayout, BorderLayout.SOUTH); timer = new Timer(); }
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 a va2 s . c o m*/ 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); }
From source file:com.gochinatv.datasync.util.Shell.java
/** * Run a command// ww w . ja v a2s . c o m */ private void runCommand() throws IOException { ProcessBuilder builder = new ProcessBuilder(getExecString()); Timer timeOutTimer = null; ShellTimeoutTimerTask timeoutTimerTask; timedOut = new AtomicBoolean(false); completed = new AtomicBoolean(false); if (environment != null) { builder.environment().putAll(this.environment); } if (dir != null) { builder.directory(this.dir); } process = builder.start(); if (timeOutInterval > 0) { timeOutTimer = new Timer(); timeoutTimerTask = new ShellTimeoutTimerTask(this); //One time scheduling. timeOutTimer.schedule(timeoutTimerTask, timeOutInterval); } final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream())); final StringBuffer errMsg = new StringBuffer(); // read error and input streams as this would free up the buffers // free the error stream buffer Thread errThread = new Thread() { @Override public void run() { try { String line = errReader.readLine(); while ((line != null) && !isInterrupted()) { errMsg.append(line); errMsg.append(System.getProperty("line.separator")); line = errReader.readLine(); } } catch (IOException ioe) { LOG.warn("Error reading the error stream", ioe); } } }; try { errThread.start(); } catch (IllegalStateException ignored) { } try { parseExecResult(inReader); // parse the output // clear the input stream buffer String line = inReader.readLine(); while (line != null) { line = inReader.readLine(); } // wait for the process to finish and check the exit code exitCode = process.waitFor(); try { // make sure that the error thread exits errThread.join(); } catch (InterruptedException ie) { LOG.warn("Interrupted while reading the error stream", ie); } completed.set(true); //the timeout thread handling //taken care in finally block if (exitCode != 0) { throw new ExitCodeException(exitCode, errMsg.toString()); } } catch (InterruptedException ie) { throw new IOException(ie.toString()); } finally { if ((timeOutTimer != null) && !timedOut.get()) { timeOutTimer.cancel(); } // close the input stream try { inReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the input stream", ioe); } if (!completed.get()) { errThread.interrupt(); } try { errReader.close(); } catch (IOException ioe) { LOG.warn("Error while closing the error stream", ioe); } process.destroy(); lastTime = System.currentTimeMillis(); } }
From source file:com.jredrain.startup.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/*from ww w. j a v a2 s . com*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[redrain]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = RedRain.StatusCode.ERROR_EXEC.getValue(); } if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[redrain]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[redrain]:error:{}", e); } } if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[redrain]:execute result:{}", response.toString()); watchdog.stop(); return response; }
From source file:com.andrada.sitracker.ui.fragment.AuthorsFragment.java
/** * Crouton click handler/*from w ww . j a va 2 s .c om*/ * * @param view being clicked */ @Override public void onClick(@NotNull View view) { if (view.getId() == R.id.retryUpdateButton) { if (this.mNoNetworkCrouton != null) { Crouton.hide(this.mNoNetworkCrouton); this.mNoNetworkCrouton = null; } Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { FragmentActivity activity = getActivity(); if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { menuRefreshSelected(); } }); } } }, 1500); } }