List of usage examples for java.util Timer Timer
public Timer(String name)
From source file:eu.stratosphere.nephele.profiling.impl.TaskManagerProfilerImpl.java
public TaskManagerProfilerImpl(InetAddress jobManagerAddress, InstanceConnectionInfo instanceConnectionInfo) throws ProfilingException { // Create RPC stub for communication with job manager's profiling component. final InetSocketAddress profilingAddress = new InetSocketAddress(jobManagerAddress, GlobalConfiguration .getInteger(ProfilingUtils.JOBMANAGER_RPC_PORT_KEY, ProfilingUtils.JOBMANAGER_DEFAULT_RPC_PORT)); ProfilerImplProtocol jobManagerProfilerTmp = null; try {/* w w w .java2 s . c o m*/ jobManagerProfilerTmp = (ProfilerImplProtocol) RPC.getProxy(ProfilerImplProtocol.class, profilingAddress, NetUtils.getSocketFactory()); } catch (IOException e) { throw new ProfilingException(StringUtils.stringifyException(e)); } this.jobManagerProfiler = jobManagerProfilerTmp; // Initialize MX interface and check if thread contention monitoring is supported this.tmx = ManagementFactory.getThreadMXBean(); if (this.tmx.isThreadContentionMonitoringSupported()) { this.tmx.setThreadContentionMonitoringEnabled(true); } else { throw new ProfilingException("The thread contention monitoring is not supported."); } // Create instance profiler this.instanceProfiler = new InstanceProfiler(instanceConnectionInfo); // Set and trigger timer this.timerInterval = (long) (GlobalConfiguration.getInteger(ProfilingUtils.TASKMANAGER_REPORTINTERVAL_KEY, ProfilingUtils.DEFAULT_TASKMANAGER_REPORTINTERVAL) * 1000); // The initial delay is based on a random value, so the task managers will not send data to the job manager all // at once. final long initialDelay = (long) (Math.random() * this.timerInterval); this.timer = new Timer(true); this.timer.schedule(this, initialDelay, this.timerInterval); }
From source file:org.n52.io.PreRenderingTask.java
public void startTask() { if (taskToRun != null) { this.enabled = true; Timer timer = new Timer("Prerender charts timer task"); timer.schedule(taskToRun, 10000, getPeriodInMilliseconds()); }/*from w ww .j a v a 2 s . c o m*/ }
From source file:de.xirp.io.comm.lowlevel.AbstractStreamCommunicationInterface.java
/** * Sends data periodically.// ww w .ja v a2s .c o m * * @param name * the name to use for the send timer * @param time * the time interval in milliseconds between two sends * @param data * the data to send * @throws InvalidNameException * if the name is already in use */ public void sendPeriodically(String name, int time, byte[] data) throws InvalidNameException { if (periodicSenders.get(name) != null) { throw new InvalidNameException( I18n.getString("AbstractCommunication.log.alreadyExcecutingThread") + name); //$NON-NLS-1$ } Timer timer = new Timer(name); timer.schedule(getSendPeriodicTask(data), 0, time); periodicSenders.put(name, timer); }
From source file:net.grinder.AgentController.java
/** * Run the agent controller./*from w w w . jav a 2 s . c o m*/ * * @throws GrinderException occurs when the test execution is failed. */ @SuppressWarnings("ConstantConditions") public void run() throws GrinderException { synchronized (m_eventSyncCondition) { m_eventSyncCondition.notifyAll(); } StartGrinderMessage startMessage = null; ConsoleCommunication consoleCommunication = null; m_fanOutStreamSender = new FanOutStreamSender(GrinderConstants.AGENT_CONTROLLER_FANOUT_STREAM_THREAD_COUNT); m_timer = new Timer(false); AgentDaemon agent = new AgentDaemon( checkNotNull(agentConfig, "agent.conf should be provided before agent daemon start.")); try { while (true) { do { if (consoleCommunication == null) { final Connector connector = m_connectorFactory.create(agentConfig.getControllerIP(), agentConfig.getControllerPort()); try { consoleCommunication = new ConsoleCommunication(connector); consoleCommunication.start(); LOGGER.info("Connected to agent controller server at {}", connector.getEndpointAsString()); } catch (CommunicationException e) { LOGGER.error("Error while connecting to agent controller server at {}", connector.getEndpointAsString()); return; } } if (consoleCommunication != null && startMessage == null) { if (m_state == AgentControllerState.UPDATING) { m_agentControllerServerListener.waitForMessage(); break; } else { LOGGER.info("Waiting for agent controller server signal"); m_state = AgentControllerState.READY; m_agentControllerServerListener.waitForMessage(); if (m_agentControllerServerListener.received(AgentControllerServerListener.START)) { startMessage = m_agentControllerServerListener.getLastStartGrinderMessage(); LOGGER.info("Agent start message is received from controller {}", startMessage); continue; } else { break; // Another message, check at end of outer // while loop. } } } if (startMessage != null) { m_agentIdentity.setNumber(startMessage.getAgentNumber()); } } while (checkNotNull(startMessage).getProperties() == null); // Here the agent run code goes.. if (startMessage != null) { final String testId = startMessage.getProperties().getProperty("grinder.test.id", "unknown"); LOGGER.info("Starting agent... for {}", testId); m_state = AgentControllerState.BUSY; m_connectionPort = startMessage.getProperties().getInt(GrinderProperties.CONSOLE_PORT, 0); agent.run(startMessage.getProperties()); final ConsoleCommunication conCom = consoleCommunication; agent.resetListeners(); agent.addListener(new AgentShutDownListener() { @Override public void shutdownAgent() { LOGGER.info("Send log for {}", testId); sendLog(conCom, testId); m_state = AgentControllerState.READY; m_connectionPort = 0; } }); } // Ignore any pending start messages. m_agentControllerServerListener.discardMessages(AgentControllerServerListener.START); if (!m_agentControllerServerListener.received(AgentControllerServerListener.ANY)) { // We've got here naturally, without a console signal. LOGGER.info("Agent is started. Waiting for agent controller signal"); m_agentControllerServerListener.waitForMessage(); } if (m_agentControllerServerListener.received(AgentControllerServerListener.START)) { startMessage = m_agentControllerServerListener.getLastStartGrinderMessage(); } else if (m_agentControllerServerListener.received(AgentControllerServerListener.STOP)) { agent.shutdown(); startMessage = null; m_connectionPort = 0; m_agentControllerServerListener.discardMessages(AgentControllerServerListener.STOP); } else if (m_agentControllerServerListener.received(AgentControllerServerListener.SHUTDOWN)) { m_connectionPort = 0; break; } else if (m_agentControllerServerListener.received(AgentControllerServerListener.AGENT_UPDATE)) { // Do update agent by downloading new version. startMessage = null; m_connectionPort = 0; m_state = AgentControllerState.UPDATING; final AgentUpdateGrinderMessage message = m_agentControllerServerListener .getLastAgentUpdateGrinderMessage(); m_agentControllerServerListener.discardMessages(AgentControllerServerListener.AGENT_UPDATE); AgentDownloadGrinderMessage agentDownloadGrinderMessage = new AgentDownloadGrinderMessage( message.getVersion()); try { // If it's initial message if (agentUpdateHandler == null && message.getNext() == 0) { IOUtils.closeQuietly(agentUpdateHandler); agentUpdateHandler = new AgentUpdateHandler(agentConfig, message); } else if (agentUpdateHandler != null) { if (message.isValid()) { retryCount = 0; agentUpdateHandler.update(message); agentDownloadGrinderMessage.setNext(message.getNext()); } else if (retryCount <= AgentDownloadGrinderMessage.MAX_RETRY_COUNT) { retryCount++; agentDownloadGrinderMessage.setNext(message.getOffset()); } else { throw new CommunicationException( "Error while getting the agent package from " + "controller"); } } else { throw new CommunicationException( "Error while getting the agent package from controller"); } if (consoleCommunication != null) { consoleCommunication.sendMessage(agentDownloadGrinderMessage); } else { break; } } catch (IllegalArgumentException ex) { IOUtils.closeQuietly(agentUpdateHandler); agentUpdateHandler = null; retryCount = 0; LOGGER.info("same or old agent version {} is sent for update. skip this.", message.getVersion()); m_state = AgentControllerState.READY; } catch (Exception e) { retryCount = 0; IOUtils.closeQuietly(agentUpdateHandler); agentUpdateHandler = null; LOGGER.error("While updating agent, the exception occurred.", e); m_state = AgentControllerState.READY; } } else { // ConsoleListener.RESET or natural death. startMessage = null; } } } finally { m_connectionPort = 0; // Abnormal state. agent.shutdown(); m_state = AgentControllerState.FINISHED; shutdownConsoleCommunication(consoleCommunication); m_timer.cancel(); } }
From source file:co.rsk.mine.MinerServerImpl.java
@Override public void start() { ethereum.addListener(new NewBlockListener()); buildBlockToMine(blockchain.getBestBlock(), false); new Timer("Refresh work for mining").schedule(new RefreshBlock(), DELAY_BETWEEN_BUILD_BLOCKS_MS, DELAY_BETWEEN_BUILD_BLOCKS_MS); }
From source file:dk.netarkivet.wayback.aggregator.AggregationWorker.java
/** * Starts the aggregation task. Only allowed to be called once to avoid aggregation race conditions. *///w w w .j a v a 2 s. c om private void startAggregationThread() { if (aggregatorTask == null) { aggregatorTask = new TimerTask() { @Override public void run() { runAggregation(); } }; Timer aggregatorThreadTimer = new Timer("AggregatorThread"); aggregatorThreadTimer.schedule(aggregatorTask, 0, Settings.getLong(WaybackSettings.WAYBACK_AGGREGATOR_AGGREGATION_INTERVAL)); } else { throw new IllegalStateException("An attempt has been made to start a second aggregation job"); } }
From source file:net.grinder.engine.agent.AgentImplementationEx.java
/** * Run the Grinder agent process.//from w w w . j a v a 2s . co m * * @param grinderProperties {@link GrinderProperties} which contains grinder agent base configuration. * @throws GrinderException If an error occurs. */ public void run(GrinderProperties grinderProperties) throws GrinderException { StartGrinderMessage startMessage = null; ConsoleCommunication consoleCommunication = null; m_fanOutStreamSender = new FanOutStreamSender(GrinderConstants.AGENT_FANOUT_STREAM_THREAD_COUNT); m_timer = new Timer(false); try { while (true) { m_logger.info(GrinderBuild.getName()); ScriptLocation script = null; GrinderProperties properties; do { properties = createAndMergeProperties(grinderProperties, startMessage != null ? startMessage.getProperties() : null); properties.setProperty(GrinderProperties.CONSOLE_HOST, m_agentConfig.getControllerIP()); m_agentIdentity.setName(m_agentConfig.getAgentHostID()); final Connector connector = m_connectorFactory.create(properties); // We only reconnect if the connection details have changed. if (consoleCommunication != null && !consoleCommunication.getConnector().equals(connector)) { shutdownConsoleCommunication(consoleCommunication); consoleCommunication = null; // Accept any startMessage from previous console - see // bug 2092881. } if (consoleCommunication == null && connector != null) { try { consoleCommunication = new ConsoleCommunication(connector, grinderProperties.getProperty("grinder.user", "_default")); consoleCommunication.start(); m_logger.info("Connect to console at {}", connector.getEndpointAsString()); } catch (CommunicationException e) { if (m_proceedWithoutConsole) { m_logger.warn( "{}, proceeding without the console; set " + "grinder.useConsole=false to disable this warning.", e.getMessage()); } else { m_logger.error(e.getMessage()); return; } } } if (consoleCommunication != null && startMessage == null) { m_logger.info("Waiting for console signal"); m_consoleListener.waitForMessage(); if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); continue; // Loop to handle new properties. } else { break; // Another message, check at end of outer while loop. } } if (startMessage != null) { final GrinderProperties messageProperties = startMessage.getProperties(); final Directory fileStoreDirectory = m_fileStore.getDirectory(); // Convert relative path to absolute path. messageProperties.setAssociatedFile( fileStoreDirectory.getFile(messageProperties.getAssociatedFile())); final File consoleScript = messageProperties.resolveRelativeFile(messageProperties .getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); // We only fall back to the agent properties if the start message // doesn't specify a script and there is no default script. if (messageProperties.containsKey(GrinderProperties.SCRIPT) || consoleScript.canRead()) { // The script directory may not be the file's direct parent. script = new ScriptLocation(fileStoreDirectory, consoleScript); } m_agentIdentity.setNumber(startMessage.getAgentNumber()); } else { m_agentIdentity.setNumber(-1); } if (script == null) { final File scriptFile = properties.resolveRelativeFile( properties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); script = new ScriptLocation(scriptFile); } m_logger.debug("The script location is {}", script.getFile().getAbsolutePath()); if (!script.getFile().canRead()) { m_logger.error("The script file '{}' does not exist or is not readable.", script); script = null; break; } } while (script == null); if (script != null) { // Set up log directory. if (!properties.containsKey(GrinderProperties.LOG_DIRECTORY)) { properties.setFile(GrinderProperties.LOG_DIRECTORY, new File(m_agentConfig.getHome().getLogDirectory(), properties.getProperty(GRINDER_PROP_TEST_ID, "default"))); } File logFile = new File(properties.getFile(GrinderProperties.LOG_DIRECTORY, new File(".")), m_agentIdentity.getName() + "-" + m_agentIdentity.getNumber() + ".log"); m_logger.info("log file : {}", logFile); AbstractLanguageHandler handler = Lang.getByFileName(script.getFile()).getHandler(); final WorkerFactory workerFactory; Properties rebasedSystemProperty = rebaseSystemClassPath(System.getProperties(), m_agentConfig.getCurrentDirectory()); String jvmArguments = buildTestRunProperties(script, handler, rebasedSystemProperty, properties); if (!properties.getBoolean("grinder.debug.singleprocess", false)) { // Fix to provide empty system classpath to speed up final WorkerProcessCommandLine workerCommandLine = new WorkerProcessCommandLine(properties, filterSystemClassPath(rebasedSystemProperty, handler, m_logger), jvmArguments, script.getDirectory()); m_logger.info("Worker process command line: {}", workerCommandLine); FileUtils.writeStringToFile(logFile, workerCommandLine.toString() + "\n\n"); workerFactory = new ProcessWorkerFactory(workerCommandLine, m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } else { m_logger.info("DEBUG MODE. Spawning threads rather than processes"); m_logger.warn("grinder.jvm.arguments ({}) ignored in single process mode", jvmArguments); workerFactory = new DebugThreadWorkerFactory(m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } m_logger.debug("Worker launcher is prepared."); final WorkerLauncher workerLauncher = new WorkerLauncher( properties.getInt("grinder.processes", 1), workerFactory, m_eventSynchronisation, m_logger); m_workerLauncherForShutdown = workerLauncher; final boolean threadRampUp = properties.getBoolean("grinder.threadRampUp", false); final int increment = properties.getInt("grinder.processIncrement", 0); if (!threadRampUp) { m_logger.debug("'Ramp Up' mode by {}.", increment); } if (!threadRampUp && increment > 0) { final boolean moreProcessesToStart = workerLauncher .startSomeWorkers(properties.getInt("grinder.initialProcesses", increment)); if (moreProcessesToStart) { final int incrementInterval = properties.getInt("grinder.processIncrementInterval", 60000); final RampUpTimerTask rampUpTimerTask = new RampUpTimerTask(workerLauncher, increment); m_timer.scheduleAtFixedRate(rampUpTimerTask, incrementInterval, incrementInterval); } } else { m_logger.debug("start all workers"); workerLauncher.startAllWorkers(); } // Wait for a termination event. synchronized (m_eventSynchronisation) { final long maximumShutdownTime = 5000; long consoleSignalTime = -1; while (!workerLauncher.allFinished()) { m_logger.debug("Waiting until all workers are finished"); if (consoleSignalTime == -1 && m_consoleListener .checkForMessage(ConsoleListener.ANY ^ ConsoleListener.START)) { m_logger.info("Don't start anymore by message from controller."); workerLauncher.dontStartAnyMore(); consoleSignalTime = System.currentTimeMillis(); } if (consoleSignalTime >= 0 && System.currentTimeMillis() - consoleSignalTime > maximumShutdownTime) { m_logger.info("Terminating unresponsive processes by force"); // destroyAllWorkers() prevents further workers // from starting. workerLauncher.destroyAllWorkers(); } m_eventSynchronisation.waitNoInterrruptException(maximumShutdownTime); } m_logger.info("All workers are finished"); } m_logger.debug("Normal shutdown"); workerLauncher.shutdown(); break; } if (consoleCommunication == null) { m_logger.debug("Console communication death"); break; } else { // Ignore any pending start messages. m_consoleListener.discardMessages(ConsoleListener.START); if (!m_consoleListener.received(ConsoleListener.ANY)) { // We've got here naturally, without a console signal. m_logger.debug("Test is finished, wait for console signal"); m_consoleListener.waitForMessage(); } if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); } else if (m_consoleListener.received(ConsoleListener.STOP | ConsoleListener.SHUTDOWN)) { m_logger.debug("Got shutdown message"); break; } else { m_logger.debug("Natural death"); // ConsoleListener.RESET or natural death. startMessage = null; } } } } catch (Exception e) { m_logger.error("Exception occurred in the agent message loop", e); } finally { if (m_timer != null) { m_timer.cancel(); m_timer = null; } shutdownConsoleCommunication(consoleCommunication); if (m_fanOutStreamSender != null) { m_fanOutStreamSender.shutdown(); m_fanOutStreamSender = null; } m_consoleListener.shutdown(); m_logger.info("Test shuts down."); } }
From source file:org.zepan.elasticsearch.river.pinboard.PinboardRiver.java
@java.lang.Override public void start() { logger.info("Starting Pinboard river"); logger.info("Pinboard index will be refreshed every {} seconds", this.fetchInterval); if (!client.admin().indices().prepareExists(indexName).execute().actionGet().exists()) { CreateIndexRequestBuilder createIndexRequest = client.admin().indices().prepareCreate(indexName); if (settings != null) { createIndexRequest.setSettings(settings); }//www . ja va2s . c o m if (mapping != null) { createIndexRequest.addMapping(typeName, mapping); } createIndexRequest.execute().actionGet(); } Timer timer = new Timer("Printer"); MyTask t = new MyTask(); timer.schedule(t, 0, this.fetchInterval * 1000); }
From source file:com.bt.aloha.sipp.SippEngineTestHelper.java
private void setUpSipp(String scenarioName, File directory, boolean respondToOriginatingAddress) throws IOException { // Give some time to settle between sipp calls. try {// w w w. ja v a 2 s . com Thread.sleep(TWO_THOUSAND); } catch (InterruptedException e) { } Properties props = new Properties(); props.load(getClass().getResourceAsStream("/sipp.properties")); final String sippPath = props.getProperty("sipp.home") + "/sipp"; String localIpAddress = setIpAddress(props.getProperty("sip.stack.ip.address.pattern")); port = Integer.parseInt(props.getProperty("sipp.local.port")); String localPortOption = props.getProperty("sipp.local.port") == null ? "" : String.format("-p %s", port); String remoteAddressOption = respondToOriginatingAddress ? "" : String.format("-rsa %s:%s", localIpAddress, props.getProperty("sip.stack.port")); String runTimesOption = "-m 1"; String remoteAddressPort = respondToOriginatingAddress ? localIpAddress : String.format("%s:%s", localIpAddress, props.getProperty("sip.stack.port")); String cmdLine = String.format("%s %s %s %s %s %s", sippPath, remoteAddressOption, runTimesOption, scenarioName, remoteAddressPort, localPortOption); log.debug(cmdLine); System.out.println("COMMAND LINE:"); System.out.println("cd " + directory.getAbsolutePath()); System.out.println(cmdLine); process = Runtime.getRuntime().exec(cmdLine, null, directory); final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); final OutputStream out = process.getOutputStream(); final BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream())); timer = new Timer(false); timer.schedule(new TimerTask() { @Override public void run() { process.destroy(); } }, 30000); final Object event = new Object(); new Thread() { public void run() { try { String line; while ((line = err.readLine()) != null) { // while (err.ready() && (line = err.readLine()) != // null) { errSB.append(line); } err.close(); } catch (IOException e) { log.debug("Unable to read the error stream from sipp", e); } } }.start(); new Thread() { public void run() { try { String line; while ((line = in.readLine()) != null) { // while (in.ready() && (line = in.readLine()) != null) // { if (line.contains("Terminated")) { break; } if (port == -1 && line.contains("Scenario Screen")) { line = in.readLine(); String pattern; int group; if (line.contains("Transport")) { pattern = "(\\d+)"; group = 1; } else if (line.contains("Remote-host")) { pattern = "(.*?\\ds.*?)(\\d+)"; group = 2; } else continue; line = in.readLine(); final Pattern pat = Pattern.compile(pattern); Matcher matcher = pat.matcher(line); matcher.find(); port = Integer.parseInt(matcher.group(group)); synchronized (event) { event.notify(); } } } in.close(); out.close(); } catch (IOException e) { log.debug("Unable to read the input stream from sipp", e); } } }.start(); synchronized (event) { try { event.wait(FIVE_THOUSAND); } catch (InterruptedException e) { } } if (port == -1) throw new IOException("Error reading sipp port"); System.out.println("Running sipp at " + getSippAddress()); }
From source file:dk.netarkivet.wayback.indexer.WaybackIndexer.java
/** * Starts the producer thread. This thread runs on a timer. It downloads a list of all files in the archive and adds * any new ones to the database. It then checks the database for unindexed files and adds them to the queue. *//* w ww .ja v a 2 s . c o m*/ private static void startProducerThread() { Long producerDelay = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_PRODUCER_DELAY); Long producerInterval = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_PRODUCER_INTERVAL); Long recentProducerInterval = Settings.getLong(WaybackSettings.WAYBACK_INDEXER_RECENT_PRODUCER_INTERVAL); TimerTask completeProducerTask = new TimerTask() { @Override public void run() { log.info("Starting producer task for all filenames"); IndexerQueue iq = IndexerQueue.getInstance(); iq.populate(); FileNameHarvester.harvestAllFilenames(); iq.populate(); } }; Timer producerThreadTimer = new Timer("ProducerThread"); producerThreadTimer.schedule(completeProducerTask, producerDelay, producerInterval); TimerTask recentProducerTask = new TimerTask() { @Override public void run() { log.info("Starting producer task for recent files"); IndexerQueue iq = IndexerQueue.getInstance(); iq.populate(); FileNameHarvester.harvestRecentFilenames(); iq.populate(); } }; producerThreadTimer.schedule(recentProducerTask, producerDelay, recentProducerInterval); }