List of usage examples for java.util Timer scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java
/** * server startup.//ww w .j av a2 s . co m * * @param properties * @throws Exception */ public void startup(Properties properties) throws Exception { configuration = new AutoExecServerConfiguration(properties); if (configuration.getProxyHost() != null) { System.setProperty("http.proxyHost", configuration.getProxyHost()); } if (configuration.getProxyPort() != null) { System.setProperty("http.proxyPort", configuration.getProxyPort()); } seleniumServer = new SeleniumServer(configuration); if (configuration.getUserExtensions() != null) { seleniumServer.addNewStaticContent(configuration.getUserExtensions().getParentFile()); } mailConfiguration = new MailConfiguration(properties); Server server = seleniumServer.getServer(); // add context HttpContext rootContext = new HttpContext(); rootContext.setContextPath(CONTEXT_PATH_ROOT); rootContext.setResourceBase(CONTENTS_DIR); rootContext.addHandler(new ResourceHandler()); server.addContext(rootContext); HttpContext commandContext = new HttpContext(); commandContext.setContextPath(CONTEXT_PATH_COMMAND); commandContext.addHandler(new CommandHandler(this)); server.addContext(commandContext); HttpContext resultContext = new HttpContext(); resultContext.setContextPath(CONTEXT_PATH_RESULT); resultContext.setResourceBase(configuration.getResultDir().getAbsolutePath()); resultContext.addHandler(new ResourceHandler()); server.addContext(resultContext); seleniumServer.start(); if (configuration.getAutoExecTime() != null) { // set auto exec timer String[] time = configuration.getAutoExecTime().split(":"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0])); calendar.set(Calendar.MINUTE, Integer.parseInt(time[1])); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); if (calendar.getTimeInMillis() < System.currentTimeMillis()) { calendar.add(Calendar.DAY_OF_MONTH, 1); } log.info("Auto exec first time: " + calendar.getTime()); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { log.info("Start auto exec."); process(); log.info("End auto exec."); } catch (Exception e) { log.error("Error auto exec."); } } }, calendar.getTime(), 1000 * 60 * 60 * 24); } log.info("Start Selenium Auto Exec Server."); }
From source file:org.ngrinder.recorder.Recorder.java
protected void initDisplayDetectionScheduledTask() { Timer timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { private Dimension prevSize; @Override//from w w w . j av a 2 s . co m public void run() { if (prevSize == null) { prevSize = getFullScreenSize(); } else { Dimension currentSize = getFullScreenSize(); if (prevSize.equals(currentSize)) { return; } if (prevSize.height > currentSize.height || prevSize.width > currentSize.width) { frame.setSize(new Dimension(600, 500)); Point currentLocation = frame.getLocation(); if (currentSize.width < currentLocation.x || currentSize.height < currentLocation.y) { frame.setLocation(200, 200); } } prevSize = currentSize; } } }, 2000, 2000); }
From source file:com.makotosan.vimeodroid.ManageTransfersActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.managetransferslayout); registerForContextMenu(getListView()); // Initialize timer Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override/*from ww w . j a v a 2 s . com*/ public void run() { handler.post(updateList); if (StaticInstances.transfers.isEmpty()) { this.cancel(); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); } } }; timer.scheduleAtFixedRate(task, 0, 3000); }
From source file:net.sf.janos.Janos.java
public void run() { Display.setAppName("Janos"); final SonosController controller = SonosController.getInstance(); try {/*from w ww. ja v a2 s . c om*/ SonosControllerShell shell = new SonosControllerShell(new Display(), controller); try { Timer zonePollerTimer = new Timer("ZonePoller", true); TimerTask zonePollerTask = new TimerTask() { @Override public void run() { controller.searchForDevices(); long pollPeriod = Long.parseLong(System.getProperty("net.sf.janos.pollPeriod", "5000")); controller.purgeStaleDevices(pollPeriod * 2); } }; long pollPeriod = Long.parseLong(System.getProperty("net.sf.janos.pollPeriod", "5000")); zonePollerTimer.scheduleAtFixedRate(zonePollerTask, 0, pollPeriod); Thread.sleep(Integer.parseInt(System.getProperty("net.sf.janos.searchTime", "1000"))); } catch (NumberFormatException e) { LogFactory.getLog(Janos.class).warn("Sleep interrupted:", e); } catch (InterruptedException e) { LogFactory.getLog(Janos.class).warn("Sleep interrupted:", e); } ApplicationContext.create(controller, shell); shell.start(); } catch (Throwable t) { LOG.fatal("Error running Janos", t); } finally { // attempt to unregister from zone players controller.dispose(); } }
From source file:Main.IrcBot.java
public void serverConnect() { try {//from ww w . j av a 2 s. com Socket ircSocket = new Socket(this.hostName, this.portNumber); if (ircSocket.isConnected()) { final PrintWriter out = new PrintWriter(ircSocket.getOutputStream(), true); final BufferedReader in = new BufferedReader(new InputStreamReader(ircSocket.getInputStream())); final BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; String pass = "PASS *"; String nick = "NICK " + this.name; String user = "USER " + this.name + " 8 * :" + this.name; String channel = "JOIN " + this.channel; Timer channelChecker = new Timer(); out.println(pass); System.out.println("echo: " + in.readLine().toString()); out.println(nick); System.out.println("echo: " + in.readLine().toString()); out.println(user); System.out.println("echo: " + in.readLine().toString()); out.println(channel); channelChecker.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { String userIn = in.readLine().toString(); ; System.out.println(userIn); if (userIn.contains("PING")) { out.println("PONG hobana.freenode.net"); } if (userIn.contains("http://pastebin.com")) { //String[] urlCode = userIn.split("[http://pastebin.com]"); String url = "http://pastebin.com"; int indexStart = userIn.indexOf(url); int indexStop = userIn.indexOf(" ", indexStart); String urlCode = userIn.substring(indexStart, indexStop); String pasteBinId = urlCode.substring(urlCode.indexOf("/", 9) + 1, urlCode.length()); System.out.println(pasteBinId); IrcBot.postRequest(pasteBinId, out); } } catch (Exception j) { } } }, 100, 100); } else { System.out.println("There was an error connecting to the IRC server: " + this.hostName + " using port " + this.portNumber); } } catch (Exception e) { //System.out.println(e.getMessage()); } }
From source file:net.resheim.eclipse.timekeeper.ui.Activator.java
private void installTaxameter() { switch (Platform.getOS()) { case Platform.OS_MACOSX: detector = new MacIdleTimeDetector(); break;/*from www.jav a 2 s. co m*/ case Platform.OS_LINUX: detector = new X11IdleTimeDetector(); break; case Platform.OS_WIN32: detector = new WindowsIdleTimeDetector(); break; default: detector = new GenericIdleTimeDetector(); break; } Timer timer = new Timer("Timekeeper", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!PlatformUI.getWorkbench().isClosing()) { long idleTimeMillis = detector.getIdleTimeMillis(); ITask task = TasksUi.getTaskActivityManager().getActiveTask(); if (null != task) { if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) { // Was idle on last check, reactivate Display.getDefault().syncExec(() -> handleReactivation(idleTimeMillis)); } else if (lastIdleTime < IDLE_INTERVAL) { String tickString = Activator.getValue(task, Activator.TICK); LocalDateTime now = LocalDateTime.now(); LocalDateTime ticked = LocalDateTime.parse(tickString); // Currently not idle so accumulate spent time accumulateTime(task, now.toLocalDate().toString(), ticked.until(now, ChronoUnit.MILLIS)); Activator.setValue(task, Activator.TICK, now.toString()); } } lastIdleTime = idleTimeMillis; } } }, SHORT_INTERVAL, SHORT_INTERVAL); // Immediately run the idle handler if the system has been idle and // the user has pressed a key or mouse button _inside_ the running // application. reactivationListener = new Listener() { public void handleEvent(Event event) { long idleTimeMillis = detector.getIdleTimeMillis(); if (idleTimeMillis < lastIdleTime && lastIdleTime > IDLE_INTERVAL) { handleReactivation(idleTimeMillis); } lastIdleTime = idleTimeMillis; } }; final Display display = PlatformUI.getWorkbench().getDisplay(); display.addFilter(SWT.KeyUp, reactivationListener); display.addFilter(SWT.MouseUp, reactivationListener); }
From source file:org.ambientdynamix.core.HomeActivity.java
@Override public void onCreate(Bundle savedInstanceState) { Log.v(TAG, "Activity State: onCreate()"); super.onCreate(savedInstanceState); // Set our static reference activity = this; setContentView(R.layout.home_tab);//from ww w. j a va2 s. co m updateCheck(); points = new HashSet<>(); mMixpanel = MixpanelAPI.getInstance(this, Constants.MIXPANEL_TOKEN); mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map_main)); // Check if we were successful in obtaining the map. if (mMap == null) { // check if google play service in the device is not available or out-dated. GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); // nothing anymore, cuz android will take care of the rest (to remind user to update google play service). } // Construct the data source sensorMeasurements = new ArrayList<>(); // Create the adapter to convert the array to views sensorMeasurementAdapter = new SensorMeasurementAdapter(this, sensorMeasurements); // Attach the adapter to a ListView final TwoWayView listView = (TwoWayView) findViewById(R.id.lvItems); listView.setOrientation(TwoWayView.Orientation.VERTICAL); listView.setPadding(0, 0, 0, 0); listView.setItemMargin(0); listView.setAdapter(sensorMeasurementAdapter); //Disable for now final Intent activityRecognitionIntent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 0, activityRecognitionIntent, PendingIntent.FLAG_UPDATE_CURRENT); mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API) .addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); pendingSendButton = (Button) findViewById(R.id.send_pending_now); pendingSendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncReportOnServerTask().execute(); try { final JSONObject props = new JSONObject(); props.put("count", DynamixService.getDataStorageSize()); //mMixpanel.track("send-stored-readings", props); } catch (JSONException ignore) { } } }); // Setup an state refresh timer, which periodically updates application // state in the appList final Timer refresher = new Timer(true); final TimerTask t = new TimerTask() { @Override public void run() { refreshData(); } }; refresher.scheduleAtFixedRate(t, 0, 5000); phoneIdTv = (TextView) this.findViewById(R.id.deviceId_label); expDescriptionTv = (TextView) this.findViewById(R.id.experiment_description); if (mMap.getMap() != null) { mMap.getMap().setMyLocationEnabled(true); mMap.getMap().getUiSettings().setAllGesturesEnabled(false); mMap.getMap().getUiSettings().setMyLocationButtonEnabled(false); } }
From source file:erigo.filepump.FilePumpWorker.java
public void run() { String output_dir_name = pumpSettings.getOutputFolder(); double files_per_sec = pumpSettings.getFilesPerSec(); int total_num_files = pumpSettings.getTotNumFiles(); FilePumpSettings.FileMode mode = pumpSettings.getMode(); String ftpHost = pumpSettings.getFTPHost(); String ftpUsername = pumpSettings.getFTPUser(); String ftpPassword = pumpSettings.getFTPPassword(); double desired_period = 1 / files_per_sec; double sleep_time_millis = desired_period * 1000; long time_used_in_last_filename = 0; Random random_generator = new Random(); int random_range = 999999; if (mode == FilePumpSettings.FileMode.LOCAL_FILESYSTEM) { if (bJustWriteEndFile) { System.err.println("\nWrite \"end.txt\" file to " + output_dir_name); } else {// w w w.j ava 2s .c om System.err.println("\nWrite files to " + output_dir_name); } } else if (mode == FilePumpSettings.FileMode.FTP) { ftpClient = new FTPClient(); try { login(ftpHost, ftpUsername, ftpPassword); } catch (Exception e) { System.err.println("Caught exception connecting to FTP server:\n" + e); return; } // Make sure we are only using "/" in output_dir_name output_dir_name = output_dir_name.replace('\\', '/'); if (bJustWriteEndFile) { System.err.println("\nWrite \"end.txt\" file out using FTP: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } else { System.err.println("\nFTP files: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } } else if (mode == FilePumpSettings.FileMode.SFTP) { // Make sure output_dir_name starts with an "/" if (output_dir_name.charAt(0) != '/') { output_dir_name = "/" + output_dir_name; } manager = new StandardFileSystemManager(); try { manager.init(); // Just use the default logger // manager.setTemporaryFileStore(new DefaultFileReplicator(new File("C:\\TEMP"))); // Code to set SFTP configuration is largely copied from a submission to the following Stack Overflow post: // https://stackoverflow.com/questions/44763915/how-to-skip-password-prompt-during-sftp-using-commons-vfs // Sample author: Som, https://stackoverflow.com/users/6416340/som // License: Stack Overflow content is covered by the Creative Commons license, https://creativecommons.org/licenses/by-sa/3.0/legalcode // Setup our SFTP configuration fileSystemOptions = new FileSystemOptions(); SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fileSystemOptions, "no"); // VFS file system root: // setting this parameter false = cause VFS to choose File System's Root as VFS's root // setting this parameter true = cause VFS to choose user's home directory as VFS's root SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileSystemOptions, true); SftpFileSystemConfigBuilder.getInstance().setTimeout(fileSystemOptions, 10000); // The following line was used by the Stack Overflow post author to be able to skip a credentials prompt // SftpFileSystemConfigBuilder.getInstance().setPreferredAuthentications(fileSystemOptions, "publickey,keyboard-interactive,password"); } catch (Exception e) { System.err.println("Caught exception setting up Apache Commons VFS manager for SFTP:\n" + e); e.printStackTrace(); return; } // Make sure we are only using "/" in output_dir_name output_dir_name = output_dir_name.replace('\\', '/'); // Create the base connection String // For example, for username "fooUser" and password "fooPW" trying to connect to 192.168.2.56 and put files in folder FooFolder: // sftp://fooUser:fooPW@192.168.2.56/FooFolder // Note that up above we made sure that output_dir_name starts with "/" baseConnectionStr = "sftp://" + ftpUsername + ":" + ftpPassword + "@" + ftpHost + output_dir_name; if (bJustWriteEndFile) { System.err.println("\nWrite \"end.txt\" file out using SFTP: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } else { System.err.println("\nSFTP files: host = " + ftpHost + ", username = " + ftpUsername + ", folder = " + output_dir_name); } } // // If out only task is to send an end.txt file, go ahead and do it and then return // if (bJustWriteEndFile) { String filename = "end.txt"; if (mode == FilePumpSettings.FileMode.FTP) { writeToFTP(output_dir_name, filename, 1); } else if (mode == FilePumpSettings.FileMode.SFTP) { writeToSFTP(filename, 1); } else { File full_filename = new File(output_dir_name, filename); FileWriter fw; try { fw = new FileWriter(full_filename, false); } catch (IOException e) { System.err.println("Caught IOException trying to create the FileWriter:\n" + e + "\n"); e.printStackTrace(); return; } PrintWriter pw = new PrintWriter(fw); pw.format("1\n"); pw.close(); } if (mode == FilePumpSettings.FileMode.FTP) { logout(); } else if (mode == FilePumpSettings.FileMode.SFTP) { manager.close(); } System.err.println("Wrote out \"end.txt\""); return; } // // Setup a periodic timer to update the file count on the GUI // TimerTask timerTask = new FileCountTimerTask(pumpGUI, this); // run timer task as daemon thread Timer timer = new Timer(true); timer.scheduleAtFixedRate(timerTask, 0, 5 * 1000); while (pumpGUI.bPumpRunning) { long start_time = System.currentTimeMillis(); // Create the next file // Always have time move forward // NOTE: The computer's clock being adjusted backward could activate this code if (start_time <= time_used_in_last_filename) { while (true) { try { Thread.sleep(1); } catch (InterruptedException ie) { // nothing to do } start_time = System.currentTimeMillis(); if (start_time > time_used_in_last_filename) { break; } } } ++file_index; String filename = Long.toString(start_time) + "_" + Integer.toString(file_index) + ".txt"; int random_num = (int) ((double) random_range * random_generator.nextDouble()); if (mode == FilePumpSettings.FileMode.FTP) { writeToFTP(output_dir_name, filename, random_num); } else if (mode == FilePumpSettings.FileMode.SFTP) { writeToSFTP(filename, random_num); } else { File full_filename = new File(output_dir_name, filename); FileWriter fw; try { fw = new FileWriter(full_filename, false); } catch (IOException e) { System.err.println("Caught IOException trying to create the FileWriter:\n" + e + "\n"); e.printStackTrace(); break; } PrintWriter pw = new PrintWriter(fw); // Write out a random number to the file pw.format("%06d\n", random_num); pw.close(); } if ((!pumpGUI.bPumpRunning) || (file_index == total_num_files)) { break; } // Sleep try { long actual_sleep_amount = (long) Math.round(sleep_time_millis); if (actual_sleep_amount > 0) { Thread.sleep(actual_sleep_amount); } } catch (InterruptedException ie) { // nothing to do } // Check how we are doing on timing and adjust the sleep time if needed long stop_time = System.currentTimeMillis(); double time_err_secs = desired_period - (double) (stop_time - start_time) / 1000.0; // Adjust sleep_time_millis based on this timing error sleep_time_millis = sleep_time_millis + 0.25 * time_err_secs * 1000.0; // Smallest sleep time is 0 if (sleep_time_millis < 0) { sleep_time_millis = 0.0; } time_used_in_last_filename = start_time; } if (mode == FilePumpSettings.FileMode.FTP) { logout(); } else if (mode == FilePumpSettings.FileMode.SFTP) { manager.close(); } timer.cancel(); // Make sure the final file count is displayed in the GUI pumpGUI.updateNumFiles_nonEDT(file_index); // If we are exiting because the requested number of files have been // reached (ie, exiting of our own volition as opposed to someone else // canceling the run), then reset the user interface if (file_index == total_num_files) { pumpGUI.resetGUI_nonEDT(); } if (!pumpGUI.bShowGUI) { System.err.print("\n"); } System.err.println("Exiting FilePumpWorker; wrote out " + file_index + " files."); }
From source file:org.wso2.ws.dataservice.DBDeployer.java
public void deploy(DeploymentFileData deploymentFileData) { StringWriter errorWriter;//from ww w .j a v a 2 s .c o m String serviceStatus; errorWriter = new StringWriter(); serviceStatus = ""; try { deploymentFileData.setClassLoader(axisConfig.getSystemClassLoader()); AxisServiceGroup serviceGroup = new AxisServiceGroup(axisConfig); serviceGroup.setServiceGroupClassLoader(deploymentFileData.getClassLoader()); ArrayList serviceList = processService(deploymentFileData, serviceGroup, configCtx); DeploymentEngine.addServiceGroup(serviceGroup, serviceList, deploymentFileData.getFile().toURL(), deploymentFileData, axisConfig); log.info(Messages.getMessage("deployingws", deploymentFileData.getName())); } catch (DeploymentException de) { log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(), de.getMessage()), de); PrintWriter error_ptintWriter = new PrintWriter(errorWriter); de.printStackTrace(error_ptintWriter); serviceStatus = "Error:\n" + errorWriter.toString(); } catch (AxisFault axisFault) { log.error(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(), axisFault.getMessage()), axisFault); PrintWriter errorPrintWriter = new PrintWriter(errorWriter); axisFault.printStackTrace(errorPrintWriter); serviceStatus = "Error:\n" + errorWriter.toString(); } catch (Exception e) { if (log.isInfoEnabled()) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.info(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(), sw.getBuffer().toString())); } PrintWriter errorPrintWriter = new PrintWriter(errorWriter); e.printStackTrace(errorPrintWriter); serviceStatus = "Error:\n" + errorWriter.toString(); } catch (Throwable t) { if (log.isInfoEnabled()) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); log.info(Messages.getMessage(DeploymentErrorMsgs.INVALID_SERVICE, deploymentFileData.getName(), sw.getBuffer().toString())); } PrintWriter errorPrintWriter = new PrintWriter(errorWriter); t.printStackTrace(errorPrintWriter); serviceStatus = "Error:\n" + errorWriter.toString(); } finally { if (serviceStatus.startsWith("Error:")) { axisConfig.getFaultyServices().put(deploymentFileData.getFile().getAbsolutePath(), serviceStatus); //Registering a timer task to re-establish the database connection //& deploy the service again TimerTask faultyServiceRectifier = new FaultyServiceRectifier(axisService, deploymentFileData, configCtx, config); Timer timer = new Timer(); //Retry in 1 minute long retryIn = new Long(1000 * 60).longValue(); timer.scheduleAtFixedRate(faultyServiceRectifier, new Date(), retryIn); } } }
From source file:org.apache.jmeter.protocol.mqttws.client.MqttPubSub.java
private boolean startHeartBeat(Timer t) { try {/*from w ww .java 2 s. c o m*/ client.subscribe(heartbeatChannel, 1); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } t.scheduleAtFixedRate(heartbeatTask, 0, 1000); return true; }