List of usage examples for java.util Timer schedule
public void schedule(TimerTask task, Date firstTime, long period)
From source file:net.freifunk.android.discover.Main.java
void updateMaps() { final String URL = "https://raw.githubusercontent.com/NiJen/AndroidFreifunkNord/master/MapUrls.json"; SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); final ConnectivityManager connManager = (ConnectivityManager) getSystemService( this.getBaseContext().CONNECTIVITY_SERVICE); final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); MapMaster mapMaster = MapMaster.getInstance(); final DatabaseHelper databaseHelper = DatabaseHelper.getInstance(this.getApplicationContext()); final RequestQueueHelper requestHelper = RequestQueueHelper.getInstance(this.getApplicationContext()); final HashMap<String, NodeMap> mapList = databaseHelper.getAllNodeMaps(); final boolean sync_wifi = sharedPrefs.getBoolean("sync_wifi", true); final int sync_frequency = Integer.parseInt(sharedPrefs.getString("sync_frequency", "0")); if (sync_wifi == true) { Log.d(TAG, "Performing online update ONLY via wifi, every " + sync_frequency + " minutes"); } else {/* ww w. j a va 2s.c om*/ Log.d(TAG, "Performing online update ALWAYS, every " + sync_frequency + " minutes"); } updateTask = new TimerTask() { @Override public void run() { /* load from database */ for (NodeMap map : mapList.values()) { map.loadNodes(); } /* load from web */ if (connManager.getActiveNetworkInfo() != null && (sync_wifi == false || mWifi.isConnected() == true)) { Log.d(TAG, "Performing online update. Next update at " + scheduledExecutionTime()); requestHelper.add(new JsonObjectRequest(URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { try { MapMaster mapMaster = MapMaster.getInstance(); Iterator mapkeys = jsonObject.keys(); while (mapkeys.hasNext()) { String mapName = mapkeys.next().toString(); String mapUrl = jsonObject.getString(mapName); NodeMap m = new NodeMap(mapName, mapUrl); databaseHelper.addNodeMap(m); // only update, if not already found in database if (!mapList.containsKey(m.getMapName())) { m.loadNodes(); } } } catch (JSONException e) { Log.e(TAG, e.toString()); } finally { requestHelper.RequestDone(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Log.e(TAG, volleyError.toString()); requestHelper.RequestDone(); } })); } else { Log.d(TAG, "Online update is skipped. Next try at " + scheduledExecutionTime()); } } }; Timer timer = new Timer(); if (sync_frequency > 0) { timer.schedule(updateTask, 0, (sync_frequency * 60 * 1000)); } else { timer.schedule(updateTask, 0); } }
From source file:org.apache.camel.component.timer.TimerConsumer.java
protected void configureTask(TimerTask task, Timer timer) { if (endpoint.isFixedRate()) { if (endpoint.getTime() != null) { timer.scheduleAtFixedRate(task, endpoint.getTime(), endpoint.getPeriod()); } else {/*from w w w . java 2s .c o m*/ timer.scheduleAtFixedRate(task, endpoint.getDelay(), endpoint.getPeriod()); } } else { if (endpoint.getTime() != null) { if (endpoint.getPeriod() > 0) { timer.schedule(task, endpoint.getTime(), endpoint.getPeriod()); } else { timer.schedule(task, endpoint.getTime()); } } else { if (endpoint.getPeriod() > 0) { timer.schedule(task, endpoint.getDelay(), endpoint.getPeriod()); } else { timer.schedule(task, endpoint.getDelay()); } } } }
From source file:com.mischivous.wormysharpyloggy.wsl.GameScreen.java
/** * {@inheritDoc}// www.j av a 2s . c om */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Choose the appropriate layout for the game type. GameType type = (GameType) getIntent().getExtras().get("type"); if (type == GameType.PowerSet) { setContentView(R.layout.game_power_layout); } else { setContentView(R.layout.game_standard_layout); } // Choose the correct number of tiles possible for selection // at one time. if (type == GameType.PowerSet) { selected = new Tile[4]; } else { selected = new Tile[3]; } // Initialize the ImageView for each Tile on the Board for (int i = 0; i < boardSize; i++) { int id = getResources().getIdentifier(String.format("Tile%d", i + 1), "id", getPackageName()); tiles[i] = (ShadedImageView) findViewById(id); if (tiles[i] == null) { Log.e(TAG, String.format("Failed to set tiles[%d]. Value is null.", i)); } else { tiles[i].setTag(R.id.TILE_INDEX, i); tiles[i].setOnClickListener(this); } } // Set up the area to store found Sets in normal/time attack // modes and initialize their ImageViews. if (type == GameType.Normal || type == GameType.TimeAttack) { found = new ImageView[OptionsHelper.GetSetCount(this)][3]; for (int set = 0; set < found.length; set++) { for (int tile = 0; tile < found[set].length; tile++) { int id = getResources().getIdentifier(String.format("FoundSet%d_%d", set + 1, tile + 1), "id", getPackageName()); found[set][tile] = (ImageView) findViewById(id); if (found[set][tile] == null) { Log.e(TAG, String.format("Failed to set found[%d][%d]. Value is null.", set, tile)); } } } } StartGame(type); // Initialize the timer timeView = (TextView) findViewById(R.id.TimeView); Timer clockUpdateTimer = new Timer(); clockUpdateTimer.schedule(new TimerTask() { @Override public void run() { handler.post(updateClock); } }, 0, 200); }
From source file:uk.org.openseizuredetector.MainActivity.java
/** Called when the activity is first created. */ @Override/*from w w w . j a va 2 s . co m*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialise the User Interface setContentView(R.layout.main); /* Force display of overflow menu - from stackoverflow * "how to force use of..." */ try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { Log.v(TAG, "menubar fiddle exception: " + e.toString()); } // start timer to refresh user interface every second. Timer uiTimer = new Timer(); uiTimer.schedule(new TimerTask() { @Override public void run() { updateServerStatus(); } }, 0, 1000); }
From source file:emperior.Main.java
private static void makeContiniousCopys() { new Thread() { public void run() { final Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override/*from w ww . j a v a 2s. c o m*/ public void run() { if (mainFrame.actionPerformed) { System.out.println("Mache nun Kopie vom aktuellen File"); int selection = mainFrame.jTabbedPane.getSelectedIndex(); String filePath = mainFrame.jTabbedPane.getToolTipTextAt(selection); try { copyFile(filePath, getTargetLocation()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } MainFrame.actionPerformed = false; } }; timer.schedule(task, 0, 3000); } }.start(); }
From source file:eu.project.ttc.engines.morpho.CompostAE.java
@Override public void collectionProcessComplete() throws AnalysisEngineProcessException { SubTaskObserver observer = observerResource.getTaskObserver(TASK_NAME); observer.setTotalTaskWork(termIndexResource.getTermIndex().getWords().size()); LOGGER.info("Starting morphologyical compound detection for TermIndex {}", this.termIndexResource.getTermIndex().getName()); LOGGER.debug(this.toString()); wrMeasure = termIndexResource.getTermIndex().getWRMeasure(); swtLemmaIndex = termIndexResource.getTermIndex().getCustomIndex(TermIndexes.SINGLE_WORD_LEMMA); buildCompostIndex();//from www. jav a2 s.c o m final MutableLong cnt = new MutableLong(0); Timer progressLoggerTimer = new Timer("Morphosyntactic splitter AE"); progressLoggerTimer.schedule(new TimerTask() { @Override public void run() { int total = termIndexResource.getTermIndex().getWords().size(); CompostAE.LOGGER.info("Progress: {}% ({} on {})", String.format("%.2f", ((float) cnt.longValue() * 100) / total), cnt.longValue(), total); } }, 5000l, 5000l); int observingStep = 100; for (Term swt : termIndexResource.getTermIndex().getTerms()) { if (!swt.isSingleWord()) continue; cnt.increment(); if (cnt.longValue() % observingStep == 0) { observer.work(observingStep); } /* * Do not do native morphology splitting * if a composition already exists. */ Word word = swt.getWords().get(0).getWord(); if (word.isCompound()) continue; Map<Segmentation, Double> scores = computeScores(word.getLemma()); if (scores.size() > 0) { List<Segmentation> segmentations = Lists.newArrayList(scores.keySet()); /* * compare segmentations in a deterministic way. */ segmentations.sort(new Comparator<Segmentation>() { @Override public int compare(Segmentation o1, Segmentation o2) { int comp = Double.compare(scores.get(o2), scores.get(o1)); if (comp != 0) return comp; comp = Integer.compare(o1.getSegments().size(), o2.getSegments().size()); if (comp != 0) return comp; for (int i = 0; i < o1.getSegments().size(); i++) { comp = Integer.compare(o2.getSegments().get(i).getEnd(), o1.getSegments().get(i).getEnd()); if (comp != 0) return comp; } return 0; } }); Segmentation bestSegmentation = segmentations.get(0); // build the word component from segmentation WordBuilder builder = new WordBuilder(word); for (Segment seg : bestSegmentation.getSegments()) { String lemma = segmentLemmaCache.getUnchecked(seg.getLemma()); builder.addComponent(seg.getBegin(), seg.getEnd(), lemma); if (seg.isNeoclassical()) builder.setCompoundType(CompoundType.NEOCLASSICAL); else builder.setCompoundType(CompoundType.NATIVE); } builder.create(); // log the word composition if (LOGGER.isTraceEnabled()) { List<String> componentStrings = Lists.newArrayList(); for (Component component : word.getComponents()) componentStrings.add(component.toString()); LOGGER.trace("{} [{}]", word.getLemma(), Joiner.on(' ').join(componentStrings)); } } } //finalize progressLoggerTimer.cancel(); LOGGER.debug("segment score cache size: {}", segmentScoreEntries.size()); LOGGER.debug("segment score hit count: " + segmentScoreEntries.stats().hitCount()); LOGGER.debug("segment score hit rate: " + segmentScoreEntries.stats().hitRate()); LOGGER.debug("segment score eviction count: " + segmentScoreEntries.stats().evictionCount()); termIndexResource.getTermIndex().dropCustomIndex(TermIndexes.SINGLE_WORD_LEMMA); segmentScoreEntries.invalidateAll(); segmentLemmaCache.invalidateAll(); }
From source file:org.pentaho.di.ui.spoon.trans.StepPerformanceSnapShotDialog.java
public void open() { shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell);//from w w w.j ava 2 s. c o m shell.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Title")); shell.setImage(GUIResource.getInstance().getImageLogoSmall()); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); // Display 2 lists with the data types and the steps on the left side. // Then put a canvas with the graph on the right side // dataList = new org.eclipse.swt.widgets.List(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER); props.setLook(dataList); dataList.setItems(dataChoices); dataList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { // If there are multiple selections here AND there are multiple selections in the steps list, we only take the // first step in the selection... // if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) { stepsList.setSelection(stepsList.getSelectionIndices()[0]); } updateGraph(); } }); FormData fdDataList = new FormData(); fdDataList.left = new FormAttachment(0, 0); fdDataList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN); fdDataList.top = new FormAttachment(0, 0); fdDataList.bottom = new FormAttachment(30, 0); dataList.setLayoutData(fdDataList); stepsList = new org.eclipse.swt.widgets.List(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER); props.setLook(stepsList); stepsList.setItems(steps); stepsList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { // If there are multiple selections here AND there are multiple selections in the data list, we only take the // first data item in the selection... // if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) { dataList.setSelection(dataList.getSelectionIndices()[0]); } updateGraph(); } }); FormData fdStepsList = new FormData(); fdStepsList.left = new FormAttachment(0, 0); fdStepsList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN); fdStepsList.top = new FormAttachment(dataList, Const.MARGIN); fdStepsList.bottom = new FormAttachment(100, Const.MARGIN); stepsList.setLayoutData(fdStepsList); canvas = new Canvas(shell, SWT.NONE); props.setLook(canvas); FormData fdCanvas = new FormData(); fdCanvas.left = new FormAttachment(props.getMiddlePct() / 2, 0); fdCanvas.right = new FormAttachment(100, 0); fdCanvas.top = new FormAttachment(0, 0); fdCanvas.bottom = new FormAttachment(100, 0); canvas.setLayoutData(fdCanvas); shell.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent event) { updateGraph(); } }); shell.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { if (image != null) { image.dispose(); } } }); canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { if (image != null) { event.gc.drawImage(image, 0, 0); } } }); // Refresh automatically every 5 seconds as well. // Timer timer = new Timer("step performance snapshot dialog Timer"); timer.schedule(new TimerTask() { public void run() { updateGraph(); } }, 0, 5000); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } }
From source file:org.electroteque.jscrambler.JScramblerProjectTask.java
/** * run the api comment/*from w ww. j a v a 2s. c o m*/ * @throws BuildException */ public void execute() throws BuildException { try { //request the new build from the client given by the selected params jscrambler = new JScrambler(accessKey, secretKey, apiUrl, port); String result = jscrambler.post("/code.json", params); System.out.println(result); System.out.println(params); JSONObject json; try { json = new JSONObject(result); } catch (org.json.JSONException ignore) { throw new BuildException("Failed to decode json GET response."); } if (!json.has("id") || json.has("error")) { throw new BuildException("Something went wrong.\n" + result); } projectId = json.getString("id"); Timer timer = new Timer("ProjectStatus"); ProjectCheckTask t = new ProjectCheckTask(); //store the project id into an ant property for later use this.getProject().setNewProperty("jscrambler.projectId", projectId); //scheduler to check if the build has finished timer.schedule(t, 0, 2000); } catch (Exception e) { throw new BuildException(e); } }
From source file:org.pepstock.jem.node.OutputSystem.java
/** * Constructs the object and unique instance inside the node.<br> * Checks if output path exists, otherwise creates it. If exists but it's * not a directory, an exception occurs. Checks if data path exists, * otherwise an exception occurs. If exists but it's not a directory, an * exception occurs./*from ww w . j a v a 2 s. c om*/ * * @param outputpath is the path where the stored all output files of job * execution * @param datapath is the path where the datasets and files should be * stored. * @param persistencepath is the path where db files, needed for the * persistence of the clusters queue and maps, are stored * @throws ConfigurationException occurs if parameters are wrong */ public OutputSystem(String outputpath, String persistencepath) throws ConfigurationException { currentPath = new File(CURRENT_PATH); if (!currentPath.exists()) { throw new ConfigurationException(NodeMessage.JEMC099E.toMessage().getFormattedMessage(CURRENT_PATH)); } outputPath = new File(outputpath); if (!outputPath.exists()) { boolean isCreated = outputPath.mkdir(); if (isCreated) { LogAppl.getInstance().emit(NodeMessage.JEMC026I, outputPath.getAbsolutePath()); } else { throw new ConfigurationException(NodeMessage.JEMC153E.toMessage().getFormattedMessage(outputPath)); } } else if (!outputPath.isDirectory()) { throw new ConfigurationException(NodeMessage.JEMC098E.toMessage().getFormattedMessage(outputPath)); } persistencePath = new File(persistencepath); if (!persistencePath.exists()) { throw new ConfigurationException(NodeMessage.JEMC099E.toMessage().getFormattedMessage(persistencePath)); } else if (!persistencePath.isDirectory()) { throw new ConfigurationException(NodeMessage.JEMC098E.toMessage().getFormattedMessage(persistencePath)); } String className = FilenameUtils.getExtension(this.getClass().getName()); Timer timer = new Timer(className, false); timer.schedule(new GlobalFileSystemHealthCheck(), 20 * TimeUtils.SECOND, 1 * TimeUtils.MINUTE); }
From source file:com.mellanox.hadoop.mapred.UdaPlugin.java
protected void launchCppSide(boolean isNetMerger, UdaCallable _callable) { //only if this is the provider, start the periodic log check task. if (!isNetMerger) { LOG.debug("starting periodic log check task"); Timer timer = new Timer(); timer.schedule(new TaskLogLevel(), 0, 1000); }//from w w w . j a va2s .c o m LOG.debug("Launching C++ thru JNI"); buildCmdParams(); LOG.info("going to execute C++ thru JNI with argc=: " + mCmdParams.size() + " cmd: " + mCmdParams); String[] stringarray = mCmdParams.toArray(new String[0]); // if parameter is set to "true", UDA will log into its own files. Boolean log_to_uda_file = mjobConf.getBoolean("mapred.uda.log.to.unique.file", false); try { UdaBridge.start(isNetMerger, stringarray, LOG, log_level, log_to_uda_file, _callable); } catch (UnsatisfiedLinkError e) { LOG.warn("UDA: Exception when launching child"); LOG.warn("java.library.path=" + System.getProperty("java.library.path")); LOG.warn(StringUtils.stringifyException(e)); throw (e); } }