List of usage examples for java.util Timer Timer
public Timer(String name)
From source file:de.btobastian.javacord.utils.DiscordWebsocketAdapter.java
/** * Starts the heartbeat./* w w w. jav a 2 s .c o m*/ * * @param websocket The websocket the heartbeat should be sent to. * @param heartbeatInterval The heartbeat interval. * @return The timer used for the heartbeat. */ private Timer startHeartbeat(final WebSocket websocket, final int heartbeatInterval) { final Timer timer = new Timer(true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { /* if (heartbeatAckReceived) { temporally removed */ heartbeatAckReceived = false; sendHeartbeat(websocket); logger.debug("Sent heartbeat (interval: {})", heartbeatInterval); /*} else { logger.info("We did not receive an answer to our last heartbeat. Trying to reconnect!"); websocket.sendClose(1002); }*/ } }, 0, heartbeatInterval); return timer; }
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 {//from ww w. j a v a 2 s .c o m 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:edu.cens.loci.sensors.AccelerometerHandler.java
private void startChkTimer() { mFlag = false;/*ww w.ja va 2s .co m*/ mChkTimer = new Timer(TIMER_CHECK_ACC); mChkTimer.scheduleAtFixedRate(new TimerTask() { public void run() { if (isOn() && !mFlag) { MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Movement Detector is not receiving Accel data. restart handler."); if (isOn()) stop(); Timer restartTimer = new Timer(TIMER_RESTART_ACC); restartTimer.schedule(new TimerTask() { public void run() { MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Restart Accelerometer."); start(); } }, 500); } else { MyLog.e(LociConfig.D.SYS, TAG, "[ACC] (check timer) Movement Detector OK."); } mFlag = false; } }, LociConfig.pAccWatch, LociConfig.pAccWatch); }
From source file:org.talend.mdm.workbench.serverexplorer.console.MDMServerMessageConsole.java
private synchronized void monitor() { if (timer == null) { timer = new Timer(true); }/*from w ww.j a v a 2 s . c o m*/ timer.schedule(new TimerTask() { @Override public void run() { doMonitor(); } }, 0, getRefrehFrequency()); }
From source file:com.codefollower.lealone.omid.client.TSOClient.java
public TSOClient(Configuration conf) throws IOException { state = State.DISCONNECTED;/*from w w w . j ava2 s.c o m*/ queuedOps = new ArrayBlockingQueue<Op>(200); retryTimer = new Timer(true); commitCallbacks = Collections.synchronizedMap(new HashMap<Long, CommitCallback>()); isCommittedCallbacks = Collections.synchronizedMap(new HashMap<Long, List<CommitQueryCallback>>()); createCallbacks = new ConcurrentLinkedQueue<CreateCallback>(); channel = null; LOG.info("Starting TSOClient"); // Start client with Nb of active threads = 3 as maximum. factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 3); // Create the bootstrap bootstrap = new ClientBootstrap(factory); int executorThreads = conf.getInt("tso.executor.threads", 3); bootstrap.getPipeline().addLast("executor", new ExecutionHandler( new OrderedMemoryAwareThreadPoolExecutor(executorThreads, 1024 * 1024, 4 * 1024 * 1024))); bootstrap.getPipeline().addLast("handler", this); bootstrap.setOption("tcpNoDelay", false); bootstrap.setOption("keepAlive", true); bootstrap.setOption("reuseAddress", true); bootstrap.setOption("connectTimeoutMillis", 100); String host = conf.get("tso.host"); int port = conf.getInt("tso.port", 1234); maxRetries = conf.getInt("tso.max_retries", 100); retryDelayMs = conf.getInt("tso.retry_delay_ms", 1000); if (host == null) { throw new IOException("tso.host missing from configuration"); } addr = new InetSocketAddress(host, port); connectIfNeeded(); }
From source file:com.mibr.android.intelligentreminder.INeedToo.java
private Timer getMyReceivingTimer() { if (mReceivingTimer == null) { mReceivingTimer = new Timer("WebProcessingReceivingActivities"); }//from w ww . j ava 2 s .c o m return mReceivingTimer; }