List of usage examples for java.util Timer Timer
public Timer()
From source file:deincraftlauncher.IO.download.Downloader.java
private void update() { System.out.println("downloader update #" + updateNum); updateNum++;// w w w . j a v a 2 s . co m if (instance.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:ComputeNode.java
public static void main(String[] argv) { String fileservername = "localhost"; String id = null;//from ww w.j a v a 2 s. c o m Double underLoad = null; Double overLoad = null; Double failProb = null; Double constantload = null; Pair<Double, Double> gaussian = null; String fileName = null; ArgumentHandler cli = new ArgumentHandler( "FileServer [-h] [collector address] [-u underload] " + "[-o overload] [-c constant_load|-g mean variance] " + "[-p fail_prob] [-f configfile]", "Bala Subrahmanyam Kambala, Daniel William DaCosta - " + "GPLv3 (http://www.gnu.org/copyleft/gpl.html)", ""); cli.addOption("h", "help", false, "Print this usage information."); cli.addOption("u", "underLoad", true, "Under load threshold"); cli.addOption("o", "overLoad", true, "Over load threshold"); cli.addOption("c", "constant", true, "Generate constant load"); cli.addOption("p", "probability", true, "Fail Probability(0-100)"); cli.addOption("f", "configfile", true, "The configuration file to read parameters from. " + "The default is " + defaultconf + ". " + "Command line arguments will override config file " + "arguments."); cli.addOption(OptionBuilder.withLongOpt("gaussian").hasArgs(2) .withDescription("Generate a gaussian probability model for load " + "simulation. The first parameter is the mean " + "and the second parameter is the variance.") .create('g')); // parse command line CommandLine commandLine = cli.parse(argv); if (commandLine.hasOption('h')) { cli.usage(""); System.exit(0); } if (commandLine.hasOption('u')) { // TODO : Ensure the number is within range underLoad = Double.parseDouble(commandLine.getOptionValue('u')); } if (commandLine.hasOption('o')) { // TODO : Ensure the number is within range overLoad = Double.parseDouble(commandLine.getOptionValue('o')); } if (commandLine.hasOption('p')) { // TODO : Ensure the number is within range failProb = Double.parseDouble(commandLine.getOptionValue('p')); } if (commandLine.hasOption('c')) { // TODO : Ensure the number is within range constantload = Double.parseDouble(commandLine.getOptionValue('c')); } if (commandLine.hasOption('g')) { // TODO : Ensure the number is within range gaussian = new Pair<Double, Double>(Double.parseDouble(commandLine.getOptionValues('g')[0]), Double.parseDouble(commandLine.getOptionValues('g')[1])); } // TODO: If these flags are no longer mutually exclusive this // code should be adjusted to account for whatever constraint are // needed. if ((constantload != null) && (gaussian != null)) { cli.usage("-g -c switches are mutually exclusive!\n"); System.exit(1); } if (commandLine.hasOption('f')) { fileName = commandLine.getOptionValue('f'); } if (commandLine.getArgs().length != 0) fileservername = commandLine.getArgs()[0]; System.out.println(argv); try { ComputeNode node = new ComputeNode(fileservername, underLoad, overLoad, failProb, constantload, gaussian, fileName); Naming.rebind("ComputeNode" + Integer.toString(node.getID()), node); // Scheduling heart beat message handler Timer t = new Timer(); HeartBeatHandler h = node.new HeartBeatHandler(); t.schedule(h, 0, 1 * 1000); } catch (ConnectException ce) { //lg.log(Level.SEVERE, "Server is not alive"); ce.printStackTrace(); } catch (Exception e) { //lg.log(Level.SEVERE, "Exception in file server"); e.printStackTrace(); } }
From source file:com.towson.wavyleaf.Sighting.java
protected void init() { getWindow().setBackgroundDrawable(null); Typeface tf_light = Typeface.createFromAsset(getAssets(), "fonts/roboto_light.ttf"); Typeface tf_bold = Typeface.createFromAsset(getAssets(), "fonts/roboto_bold.ttf"); tvlat = (TextView) findViewById(R.id.tv_latitude); tvlong = (TextView) findViewById(R.id.tv_longitude); tvpicnotes = (TextView) findViewById(R.id.tv_picturenotes); tvper = (TextView) findViewById(R.id.tv_percentageseen); tvper_summary = (TextView) findViewById(R.id.tv_percentageseen_summary); tvcoor = (TextView) findViewById(R.id.tv_coordinates); tvarea = (TextView) findViewById(R.id.tv_areainfested); tvarea_summary = (TextView) findViewById(R.id.tv_areainfested_summary); tv_treatment = (TextView) findViewById(R.id.tv_treatment); notes = (EditText) findViewById(R.id.notes); etarea = (EditText) findViewById(R.id.et_areainfested); b1 = (ToggleButton) findViewById(R.id.bu_1); b2 = (ToggleButton) findViewById(R.id.bu_2); b3 = (ToggleButton) findViewById(R.id.bu_3); b4 = (ToggleButton) findViewById(R.id.bu_4); b5 = (ToggleButton) findViewById(R.id.bu_5); b6 = (ToggleButton) findViewById(R.id.bu_6); cb = (CheckBox) findViewById(R.id.cb_confirm); rg = (RadioGroup) findViewById(R.id.toggleGroup); sp = (Spinner) findViewById(R.id.sp_areainfested); sp_treatment = (Spinner) findViewById(R.id.sp_treatment); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationData = (LocationApplication) getApplication(); currentEditableLocation = locationData.getLocation(); updateLocationTimer = new Timer(); TimerTask updateLocationTask = new TimerTask() { @Override//from w w w . j a v a 2s .c o m public void run() { checkLocation(); } }; updateLocationTimer.scheduleAtFixedRate(updateLocationTask, 0, FIVE_SECONDS); // Listener for EditText in Area Infested etarea.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { if (etarea.getText().length() == 0) { tvarea_summary.setText(""); } else if (etarea.getText().toString().contains("-")) { // Negative number etarea.getEditableText().clear(); Toast.makeText(getApplicationContext(), "Negative values not allowed", Toast.LENGTH_SHORT) .show(); } else { tvarea_summary.setText(etarea.getText() + " " + sp.getSelectedItem().toString()); } } public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } }); // Listener for spinner in Area Infested sp.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onNothingSelected(AdapterView<?> arg0) { } @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (etarea.getText().length() != 0) tvarea_summary.setText(etarea.getText() + " " + sp.getSelectedItem()); } }); // Adapter for area infested spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.areainfested_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp.setAdapter(adapter); // Adapter for Treatment spinner ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.treatment_array, android.R.layout.simple_spinner_item); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp_treatment.setAdapter(adapter2); // Just to be safe cb.setChecked(false); // Set all the beautiful typefaces tvlat.setTypeface(tf_light); tvlong.setTypeface(tf_light); tvcoor.setTypeface(tf_bold); tvarea.setTypeface(tf_bold); tvarea_summary.setTypeface(tf_bold); tvper.setTypeface(tf_bold); tvper_summary.setTypeface(tf_bold); tvpicnotes.setTypeface(tf_bold); tv_treatment.setTypeface(tf_bold); cb.setTypeface(tf_light); b1.setTypeface(tf_light); b2.setTypeface(tf_light); b3.setTypeface(tf_light); b4.setTypeface(tf_light); b5.setTypeface(tf_light); b6.setTypeface(tf_light); if (!locationData.isSearching()) findUsersLocation(); ib = (ImageButton) findViewById(R.id.imagebutton_sighting); // Listener for camera button ib.setOnClickListener(new OnClickListener() { public void onClick(View v) { takePicture(); } }); ib_percent = (ImageButton) findViewById(R.id.ib_percent); // Listener for help button in Percentage Infested category ib_percent.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(HELP_PERCENT); } }); ib_treatment = (ImageButton) findViewById(R.id.ib_treatment); // Listener for help button in Treatment catgeory ib_treatment.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(HELP_TREATMENT); // Toast.makeText(getApplicationContext(), "Specify the type of treatment that was done to this area", Toast.LENGTH_LONG).show(); } }); }
From source file:uk.ac.horizon.ubihelper.service.PeerManager.java
public PeerManager(Service service) { this.service = service; // Note: meant to open database on another thread?! database = new PeersOpenHelper(service).getWritableDatabase(); protocol = new MyProtocolManager(); peerConnectionListener = new OnPeerConnectionListener(protocol); remoteChannelTimer = new Timer(); wifi = (WifiManager) service.getSystemService(Service.WIFI_SERVICE); try {/* w w w .j a v a2s .c o m*/ messageDigest = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.e(TAG, "Could not get MessageDigest: " + e); } try { serverSocketChannel = ServerSocketChannel.open(); ServerSocket ss = serverSocketChannel.socket(); ss.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0)); serverPort = ss.getLocalPort(); serverSocketChannel.configureBlocking(false); } catch (IOException e) { Log.w(TAG, "Error opening ServerSocketChannel: " + e.getMessage()); } try { selector = new PeerConnectionScheduler(serverSocketChannel); selector.setListener(selectorListener); selector.start(); } catch (IOException e) { Log.w(TAG, "Error starting Selector: " + e.getMessage()); } }
From source file:dk.netarkivet.harvester.indexserver.distribute.TestIndexRequestServer.java
/** * Initialise index request server with no handlers, listening to the index JMS channel. *//*from w w w .ja va2 s . c o m*/ private TestIndexRequestServer() { maxConcurrentJobs = Settings.getLong(HarvesterSettings.INDEXSERVER_INDEXING_MAXCLIENTS); requestDir = Settings.getFile(HarvesterSettings.INDEXSERVER_INDEXING_REQUESTDIR); listeningInterval = Settings.getLong(HarvesterSettings.INDEXSERVER_INDEXING_LISTENING_INTERVAL); alwaysReturnFalseMode = Settings.getBoolean(ALWAYS_SET_ISINDEX_READY_TO_FALSE); if (alwaysReturnFalseMode) { log.info("alwaysSetIsIndexReadyToFalse is true"); } else { log.info("alwaysSetIsIndexReadyToFalse is false"); } jobsForDefaultIndex = Settings.getFile(JOBS_FOR_TESTINDEX); if (!jobsForDefaultIndex.exists()) { final String msg = "The file '" + jobsForDefaultIndex.getAbsolutePath() + "' does not exist"; log.error("The file containing job identifiers for default index '{}' does not exist", jobsForDefaultIndex.getAbsolutePath()); System.err.println(msg + ". Exiting program"); System.exit(1); } defaultIDs = readLongsFromFile(jobsForDefaultIndex); currentJobs = new HashMap<String, IndexRequestMessage>(); handlers = new EnumMap<RequestType, FileBasedCache<Set<Long>>>(RequestType.class); conn = JMSConnectionFactory.getInstance(); checkIflisteningTimer = new Timer(); }
From source file:applab.search.client.SynchronizationManager.java
/** * Make sure our background timer is scheduled. Assumes that it's called under a lock. * //from w w w .jav a 2 s. c o m * Returns true if we allocated the timer */ public boolean ensureTimerIsScheduled() { boolean scheduledTimer = false; if (this.timer == null) { this.timer = new Timer(); // TODO: should we kick off a synchronization episode immediately? If so, change the first parameter here // and modify the caller appropriately this.timer.scheduleAtFixedRate(new TimedSynchronizationTask(), SYNCHRONIZATION_START_INTERVAL, SYNCHRONIZATION_INTERVAL); scheduledTimer = true; } return scheduledTimer; }
From source file:deincraftlauncher.InstallController.java
@FXML void Continue() { if (!loggedin) { popupMessage("Fehler: Bitte zuerst erst anmelden"); } else {/*from w ww . j a va 2s . c o m*/ System.out.println("Creating config file..."); try { folder.mkdirs(); config.createNewFile(); } catch (IOException ex) { System.err.println("error creating config file: " + ex); } settings.setPassword(Password); settings.setUsername(Username); settings.setRAM(getDefaultRam()); settings.save(); /*folderLauncher = new File(targetPath + "Launcher"); System.out.println("Launcher: " + folderLauncher); folderLauncher.mkdirs(); folderGame = new File(targetPath + "Games"); folderGame.mkdirs();*/ createGameDir(targetPath); if (createDesktop.isSelected()) { createDesktopShortcut(); } popupMessage("Installation abgeschlossen. Starte Minefactory Launcher..."); mainPanel.setVisible(false); try { Thread.sleep(500); } catch (InterruptedException ex) { Logger.getLogger(InstallController.class.getName()).log(Level.SEVERE, null, ex); } File installlocation = new File(targetPath); installlocation.mkdirs(); saveConfig(); String jarFile = getDCFile(); String command = "java -jar " + jarFile; Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.exit(0); } }, 4000); try { Process p = Runtime.getRuntime().exec("cmd /C " + command); BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; try { while ((line = stdout.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println(e); } } catch (IOException ex) { Logger.getLogger(InstallController.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("Finishing setting dialog..."); }
From source file:ca.canuckcoding.wosqi.FeedViewer.java
public FeedViewer(java.awt.Frame parent, WebOSConnection wc, PackageManager pm) { super(parent); bundle = WebOSQuickInstallApp.bundle; URL bgURL = getClass().getResource("resources/background2.jpg"); background = new ImageIcon(bgURL).getImage(); initComponents();//from w w w. ja va2 s . co m loaded = false; UNKNOWN_VALUE = bundle.getString("UNKNOWN"); NO_SCREENSHOT = jLabel1.getIcon(); TAB_FILTER = new PackageFilter[] { PackageFilter.Applications, PackageFilter.Services, PackageFilter.Plugins, PackageFilter.Linux_Apps, PackageFilter.Linux_Daemons, PackageFilter.Kernels, PackageFilter.Patches, PackageFilter.Themes }; CATEGORY = new JComboBox[] { jComboBox1, jComboBox2, jComboBox3, jComboBox4, jComboBox9, jComboBox5, jComboBox6, jComboBox7 }; SEARCH = new JTextField[] { jTextField1, jTextField2, jTextField3, jTextField4, jTextField9, jTextField5, jTextField6, jTextField7 }; LIST = new JList[] { jList1, jList2, jList3, jList4, jList9, jList5, jList6, jList7, jList8 }; NAME = new JLabel[] { jLabel2, jLabel13, jLabel24, jLabel35, jLabel90, jLabel46, jLabel57, jLabel68, jLabel79 }; VERSION = new JLabel[] { jLabel5, jLabel16, jLabel27, jLabel38, jLabel93, jLabel49, jLabel60, jLabel71, jLabel82 }; DEVELOPER = new JLabel[] { jLabel9, jLabel20, jLabel31, jLabel42, jLabel97, jLabel53, jLabel64, jLabel75, jLabel86 }; LASTUPDATED = new JLabel[] { jLabel6, jLabel17, jLabel28, jLabel39, jLabel94, jLabel50, jLabel61, jLabel72, jLabel83 }; SCREENSHOT = new JLabel[] { jLabel1, jLabel12, jLabel23, jLabel34, jLabel89, jLabel45, jLabel56, jLabel67, jLabel78 }; LICENSE = new JLabel[] { jLabel10, jLabel21, jLabel32, jLabel43, jLabel98, jLabel54, jLabel65, jLabel76, jLabel87 }; FEED = new JLabel[] { jLabel7, jLabel19, jLabel30, jLabel41, jLabel96, jLabel52, jLabel63, jLabel74, jLabel85 }; DESCRIPTION_LABEL = new JLabel[] { jLabel8, jLabel18, jLabel29, jLabel40, jLabel95, jLabel51, jLabel62, jLabel73, jLabel84 }; HOMEPAGE = new JLabel[] { jLabel11, jLabel22, jLabel33, jLabel44, jLabel99, jLabel55, jLabel66, jLabel77, jLabel88 }; LICENSE_LABEL = new JLabel[] { jLabel3, jLabel15, jLabel26, jLabel37, jLabel92, jLabel48, jLabel59, jLabel70, jLabel81 }; FEED_LABEL = new JLabel[] { jLabel4, jLabel14, jLabel25, jLabel36, jLabel91, jLabel47, jLabel58, jLabel69, jLabel80 }; DESCRIPTION = new JTextPane[] { jTextPane1, jTextPane2, jTextPane3, jTextPane4, jTextPane9, jTextPane5, jTextPane6, jTextPane7, jTextPane8 }; INSTALL_BUTTON = new JButton[] { jButton2, jButton4, jButton6, jButton8, jButton18, jButton10, jButton12, jButton14, jButton16 }; packages = new ArrayList[9]; filtered = new ArrayList[9]; selected = new PackageEntry[9]; webOS = wc; pkgMgr = pm; t = new Timer(); if (!webOS.isConnected()) { DeviceInfo info = webOS.getDeviceInfo(); if (info != null && !info.model().equals(DeviceInfo.Model.Unknown.toString())) { JOptionPane.showMessageDialog(rootPane, MessageFormat.format( bundle.getString("{0}_IS_DISCONNECTED._PLEASE_RECONNECT_THEN_TRY_AGAIN."), new Object[] { info.model() })); } else { JOptionPane.showMessageDialog(rootPane, bundle.getString("DEVICE_IS_DISCONNECTED._PLEASE_RECONNECT_THEN_TRY_AGAIN.")); } t.schedule(new DoDispose(), 200); } else { for (int i = 0; i < HOMEPAGE.length; i++) { HOMEPAGE[i].setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } for (int i = 0; i < NAME.length; i++) { NAME[i].setVisible(false); } t.schedule(new DoLoad(), 200); } }
From source file:io.hawkcd.agent.Agent.java
private void startReportJobTimer() { TimerTask reportTask = new TimerTask() { @Override//from w ww .j a v a 2 s.co m public void run() { Agent.this.reportJobToServer(); } }; this.reportTimer = new Timer(); this.reportTimer.schedule(reportTask, 0, 4000); }
From source file:cz.dasnet.dasik.Dasik.java
@Override protected void onConnect() { log.info("Connected on " + getServer()); auth();/* w w w. j a v a 2 s . c o m*/ if (authed) { requestInvites(); } final Dasik bot = this; try { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { bot.joinChannels(); } }, 1000); TimerTask dumpTask = new TimerTask() { @Override public void run() { Document document = DocumentHelper.createDocument(); Element channelinfo = document.addElement("channelinfo"); for (String c : activeChannels.keySet()) { Element channel = channelinfo.addElement("channel"); Element name = channel.addElement("name"); name.setText(c); Element size = channel.addElement("size"); size.setText("" + getUsers(c).length); } Element updatetime = channelinfo.addElement("updatetime"); updatetime.setText(new Long(new Date().getTime() / 1000).toString()); try { XMLWriter writer = new XMLWriter(new FileWriter("channelinfo.xml")); writer.write(document); writer.close(); } catch (IOException ex) { log.error("Unable to dump channel info", ex); } } }; Timer dump = new Timer("dump", true); dump.schedule(dumpTask, 10000, 60000); } catch (Exception ex) { this.joinChannels(); log.error("Channel autojoin timer failed to schedule the task.", ex); } }