List of usage examples for java.util Timer Timer
public Timer(String name, boolean isDaemon)
From source file:org.eclipse.swt.examples.watchdog.TimedEventWatchdog.java
public TimedEventWatchdog(Thread uiThread, long threshold_ms) { if (uiThread == null) { throw new NullPointerException(); }//from ww w . ja v a2s . co m this.threshold_ms = threshold_ms; this.dataCollectionDelay = threshold_ms / 2; this.uiThread = uiThread; this.timer = new Timer("Monitoring data collection timer", true); this.onTickTask = new TimerTask() { @Override public void run() { poll(); } }; grabStackAt = Long.MAX_VALUE; timer.scheduleAtFixedRate(onTickTask, 0, Math.max(dataCollectionDelay / 2, 1)); }
From source file:dhtaccess.benchmark.ThroughputMeasure.java
private void start(boolean details, int repeats, int queryFreq, boolean doPut, String[] args) { this.repeats = repeats; // prepare for RPC int numAccessor = args.length; DHTAccessor[] accessorArray = new DHTAccessor[numAccessor]; try {// w w w . ja v a 2 s . c o m for (int i = 0; i < numAccessor; i++) { accessorArray[i] = new DHTAccessor(args[i]); } } catch (MalformedURLException e) { e.printStackTrace(); System.exit(1); } // generate key prefix Random rnd = new Random(System.currentTimeMillis()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < KEY_PREFIX_LENGTH; i++) { sb.append((char) ('a' + rnd.nextInt(26))); } String keyPrefix = sb.toString(); String valuePrefix = VALUE_PREFIX; // benchmarking System.out.println("Repeats " + repeats + " times."); System.out.println("Query frequency (times/sec): " + queryFreq); if (doPut) { System.out.println("Putting: " + keyPrefix + "<number>"); for (int i = 0; i < repeats; i++) { byte[] key = null, value = null; try { key = (keyPrefix + i).getBytes(ENCODE); value = (valuePrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; acc.put(key, value, TTL); } } System.out.println("Benchmarking by getting."); System.out.println("(Start getting " + INITIAL_SLEEP + " msec later.)"); Timer timer = new Timer("Benchmark driving timer", false /* isDaemon */); this.count = this.repeats; this.startTime = System.currentTimeMillis() + INITIAL_SLEEP; for (int i = 0; i < repeats; i++) { byte[] key = null; try { key = (keyPrefix + i).getBytes(ENCODE); } catch (UnsupportedEncodingException e) { e.printStackTrace(); System.exit(1); } int accIndex = rnd.nextInt(numAccessor); DHTAccessor acc = accessorArray[accIndex]; TimerTask task = new GetQuerier(acc, key, details); timer.schedule(task, new Date(this.startTime + (long) (1000.0 * i / queryFreq))); } }
From source file:com.navercorp.pinpoint.web.websocket.ActiveThreadCountHandler.java
private Timer newJavaTimer(String timerName) { return new Timer(timerName, true); }
From source file:com.github.safrain.remotegsh.server.RgshFilter.java
@Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter("charset") != null) { charset = filterConfig.getInitParameter("charset"); } else {// ww w . java 2 s. c o m charset = DEFAULT_CHARSET; } if (filterConfig.getInitParameter("shellSessionTimeout") != null) { shellSessionTimeout = Long.valueOf(filterConfig.getInitParameter("shellSessionTimeout")); } else { shellSessionTimeout = SESSION_PURGE_INTERVAL; } String scriptExtensionCharset; if (filterConfig.getInitParameter("scriptExtensionCharset") != null) { scriptExtensionCharset = filterConfig.getInitParameter("scriptExtensionCharset"); } else { scriptExtensionCharset = DEFAULT_CHARSET; } //Compile script extensions List<String> scriptExtensionPaths = new ArrayList<String>(); if (filterConfig.getInitParameter("scriptExtensions") != null) { Collections.addAll(scriptExtensionPaths, filterConfig.getInitParameter("scriptExtensions").split(",")); } else { scriptExtensionPaths.add(RESOURCE_PATH + "extension/spring.groovy"); } scriptExtensions = new HashMap<String, CompiledScript>(); for (String path : scriptExtensionPaths) { String scriptContent; try { scriptContent = getResource(path, scriptExtensionCharset); } catch (IOException e) { throw new ServletException(e); } Compilable compilable = (Compilable) createGroovyEngine(); try { CompiledScript compiledScript = compilable.compile(scriptContent); scriptExtensions.put(path, compiledScript); } catch (ScriptException e) { //Ignore exceptions while compiling script extensions,there may be compilation errors due to missing dependency log.log(Level.WARNING, String.format("Error compiling script extension '%s'", path), e); } } // Setup a timer to purge timeout shell sessions Timer timer = new Timer("Remote Groovy Shell session purge daemon", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { purgeTimeOutSessions(); } }, 0, SESSION_PURGE_INTERVAL); }
From source file:edu.wisc.jmeter.dao.JdbcMonitorDao.java
@Override public void afterPropertiesSet() throws Exception { this.setupTables(); this.purgingTimer = new Timer("JdbcMonitorDao_PurgingTimer", true); this.purgingTimer.schedule(new TimerTask() { @Override//from w w w. ja va2 s . c o m public void run() { purgeFailureLog(new Date(System.currentTimeMillis() - purgeOldFailure)); purgeRequestLog(new Date(System.currentTimeMillis() - purgeOldStatus)); purgeStatusCache(new Date(System.currentTimeMillis() - purgeStatusCache)); //HostStatus objects can be rebuilt, don't hold stuff older than 5 minutes } }, 1000 * 60, //Run 1 minute after starting 1000 * 60 * 5); //Repeat every 5 minutes }
From source file:com.lfv.yada.net.client.ClientNetworkManager.java
public ClientNetworkManager(int terminalId, ClientBundle bundle, SocketAddress serverSocketAddr, SocketAddress localhostBindSocketAddr, SocketAddress multicastSocketAddr, int multicastTTL, TerminalProperties properties) throws IOException { // Create a logger for this class log = LogFactory.getLog(getClass()); // Load terminal properties this.properties = properties; // Setup stuff this.terminalId = terminalId; this.bundle = bundle; this.serverSocketAddr = new SocketAddress(serverSocketAddr); // Resolve local host address InetAddress localHost = getLocalHostFix(); if (localHost == null) { localHost = InetAddress.getLocalHost(); if (localHost == null) throw new UnknownHostException("Could not resolve ip address of localhost"); }/*w w w.java 2 s .c o m*/ // The socket to be used for sending and receiving unicast packets DatagramSocket usocket; if (localhostBindSocketAddr.getAddress() == 0) usocket = new DatagramSocket(); else usocket = new DatagramSocket(localhostBindSocketAddr.getPort(), localhostBindSocketAddr.getInetAddress()); // The multicast socket InetAddress maddr = multicastSocketAddr.getInetAddress(); int mport = multicastSocketAddr.getPort(); MulticastSocket msocket = null; multicastAvailable = (maddr != null && mport > 0); if (multicastAvailable) { msocket = new MulticastSocket(mport); try { msocket.joinGroup(maddr); msocket.setTimeToLive(multicastTTL); } catch (SocketException ex) { log.warn("!!!"); log.warn("!!! Unable to create multicast socket! Multicasting has been disabled!"); log.warn("!!! On linux systems a default gateway must be defined, try:"); log.warn("!!! > route add default gw <some_ip_address>"); log.warn("!!!"); msocket = null; multicastAvailable = false; } } else log.warn("No multicast address or port defined, multicasting has been disabled!"); // Store the local unicast ip address and port localSocketAddr = new SocketAddress(localHost, usocket.getLocalPort()); // Create a receiver and a sender (send/recv must use the same port number) receiver = new ClientPacketReceiver(terminalId, usocket, msocket); sender = new ClientPacketSender(usocket, msocket, multicastSocketAddr); // Create a transaction mananger transactionManager = new TransactionManager(sender); receiver.setControlPacketDispatcher(transactionManager); receiver.setSendPacketDispatcher(sender); // Create a timer for handling pings timer = new Timer("Snetworkmanager", true); // Initialize packet pool PacketPool.getPool(); // Setup request handlers transactionManager.setRequestHandler(Packet.SESSION, new SessionRequestPacketHandler()); transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler()); transactionManager.setRequestHandler(Packet.INFO, new InfoRequestPacketHandler()); transactionManager.setRequestHandler(Packet.ISA, new IsaRequestPacketHandler()); transactionManager.setRequestHandler(Packet.CONNECT, new ConnectRequestPacketHandler()); transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler()); }
From source file:com.googlecode.fascinator.indexer.SolrWrapperQueueConsumer.java
/** * Start thread running// w w w . ja va 2 s. c o m * */ @Override public void run() { try { MDC.put("name", name); log.info("Starting {}...", name); // Get a connection to the broker String brokerUrl = globalConfig.getString(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL, "messaging", "url"); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl); connection = connectionFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = session.createConsumer(session.createQueue(QUEUE_ID)); consumer.setMessageListener(this); connection.start(); // Solr solr = initCore("solr"); // Timeout 'tick' for buffer (10s) timer = new Timer("SolrWrapper:" + toString(), true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkTimeout(); } }, 0, 10000); } catch (JMSException ex) { log.error("Error starting message thread!", ex); } }
From source file:com.openkm.servlet.RepositoryStartupServlet.java
/** * Start OpenKM and possible repository and database initialization *///from www . j ava 2 s . c o m public static synchronized void start() throws ServletException { SystemAuthentication systemAuth = new SystemAuthentication(); if (running) { throw new IllegalStateException("OpenKM already started"); } try { log.info("*** Repository initializing... ***"); if (Config.REPOSITORY_NATIVE) { systemAuth.enable(); DbRepositoryModule.initialize(); systemAuth.disable(); } else { JcrRepositoryModule.initialize(); } log.info("*** Repository initialized ***"); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } log.info("*** User database initialized ***"); if (!Config.REPOSITORY_NATIVE) { // Test for datastore SessionImpl si = (SessionImpl) JcrRepositoryModule.getSystemSession(); if (((RepositoryImpl) si.getRepository()).getDataStore() == null) { hasConfiguredDataStore = false; } else { hasConfiguredDataStore = true; } } // Create timers uiTimer = new Timer("Update Info", true); cronTimer = new Timer("Crontab Manager", true); uinTimer = new Timer("User Interface Notification", true); // Workflow log.info("*** Initializing workflow engine... ***"); JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext(); jbpmContext.setSessionFactory(HibernateUtil.getSessionFactory()); jbpmContext.getGraphSession(); jbpmContext.getJbpmConfiguration().getJobExecutor().start(); // startJobExecutor(); jbpmContext.close(); // Mime types log.info("*** Initializing MIME types... ***"); MimeTypeConfig.loadMimeTypes(); log.info("*** Activating update info ***"); ui = new UpdateInfo(); uiTimer.schedule(ui, TimeUnit.MINUTES.toMillis(5), TimeUnit.HOURS.toMillis(24)); // First in 5 min, next each 24 hours log.info("*** Activating cron ***"); cron = new Cron(); Calendar calCron = Calendar.getInstance(); calCron.add(Calendar.MINUTE, 1); calCron.set(Calendar.SECOND, 0); calCron.set(Calendar.MILLISECOND, 0); // Round begin to next minute, 0 seconds, 0 miliseconds cronTimer.scheduleAtFixedRate(cron, calCron.getTime(), 60 * 1000); // First in 1 min, next each 1 min log.info("*** Activating UI Notification ***"); uin = new UINotification(); // First in 1 second next in x minutes uinTimer.scheduleAtFixedRate(uin, 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_UI_NOTIFICATION)); try { // General maintenance works String dapContent = "com.openkm.dao.DashboardActivityDAO.purge();"; CronTabUtils.createOrUpdate("Dashboard Activity Purge", "@daily", dapContent); String uisContent = "com.openkm.cache.UserItemsManager.serialize();"; CronTabUtils.createOrUpdate("User Items Serialize", "@hourly", uisContent); String ruiContent = "com.openkm.cache.UserItemsManager.refreshDbUserItems();"; CronTabUtils.createOrUpdate("Refresh User Items", "@weekly", ruiContent); String umiContent = "new com.openkm.core.UserMailImporter().run();"; CronTabUtils.createOrUpdate("User Mail Importer", "*/30 * * * *", umiContent); String tewContent = "new com.openkm.extractor.TextExtractorWorker().run();"; CronTabUtils.createOrUpdate("Text Extractor Worker", "*/5 * * * *", tewContent); String swdContent = "new com.openkm.core.Watchdog().run();"; CronTabUtils.createOrUpdate("Session Watchdog", "*/5 * * * *", swdContent); String pptContent = "new com.openkm.util.pendtask.PendingTaskExecutor().run();"; CronTabUtils.createOrUpdate("Process Pending Tasks", "*/5 * * * *", pptContent); // Datastore garbage collection if (!Config.REPOSITORY_NATIVE && hasConfiguredDataStore) { String dgcContent = "new com.openkm.module.jcr.stuff.DataStoreGarbageCollector().run();"; CronTabUtils.createOrUpdate("Datastore Garbage Collector", "@daily", dgcContent); } } catch (Exception e) { log.warn(e.getMessage(), e); } try { log.info("*** Activating thesaurus repository ***"); RDFREpository.getInstance(); } catch (Exception e) { log.warn(e.getMessage(), e); } try { if (Config.REMOTE_CONVERSION_SERVER.equals("")) { if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) { log.info("*** Start OpenOffice manager ***"); DocConverter.getInstance().start(); } else if (!Config.SYSTEM_OPENOFFICE_SERVER.equals("")) { log.info("*** Using OpenOffice conversion server ***"); } else { log.warn("*** No OpenOffice manager nor server configured ***"); } } else { log.info("*** Remote conversion configured ***"); } } catch (Throwable e) { log.warn(e.getMessage(), e); } // Initialize plugin framework ExtensionManager.getInstance(); try { log.info("*** Execute start script ***"); File script = new File(Config.HOME_DIR + File.separatorChar + Config.START_SCRIPT); ExecutionUtils.runScript(script); File jar = new File(Config.HOME_DIR + File.separatorChar + Config.START_JAR); ExecutionUtils.getInstance().runJar(jar); } catch (Throwable e) { log.warn(e.getMessage(), e); } try { log.info("*** Execute start SQL ***"); File sql = new File(Config.HOME_DIR + File.separatorChar + Config.START_SQL); if (sql.exists() && sql.canRead()) { FileReader fr = new FileReader(sql); HibernateUtil.executeSentences(fr); IOUtils.closeQuietly(fr); } else { log.warn("Unable to read sql: {}", sql.getPath()); } } catch (Throwable e) { log.warn(e.getMessage(), e); } // OpenKM is started running = true; }
From source file:com.predic8.membrane.core.exchangestore.FileExchangeStore.java
public void initializeTimer() { if (this.maxDays < 0) { return; // don't do anything if this feature is deactivated }//from w w w. j a v a 2s. com oldFilesCleanupTimer = new Timer("Clean up old log files", true); // schedule first run for the night Calendar firstRun = Calendar.getInstance(); firstRun.set(Calendar.HOUR_OF_DAY, 3); firstRun.set(Calendar.MINUTE, 14); // schedule for the next day if the scheduled execution time is before now if (firstRun.before(Calendar.getInstance())) firstRun.add(Calendar.DAY_OF_MONTH, 1); oldFilesCleanupTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { deleteOldFolders(); } catch (IOException e) { log.error("", e); } } }, firstRun.getTime(), 24 * 60 * 60 * 1000 // one day ); }
From source file:com.ikon.servlet.RepositoryStartupServlet.java
/** * Start openkm and possible repository and database initialization *//*from w w w.j a v a2s . c o m*/ public static synchronized void start() throws ServletException { SystemAuthentication systemAuth = new SystemAuthentication(); if (running) { throw new IllegalStateException("openkm already started"); } try { log.info("*** Repository initializing... ***"); if (Config.REPOSITORY_NATIVE) { systemAuth.enable(); DbRepositoryModule.initialize(); systemAuth.disable(); } else { JcrRepositoryModule.initialize(); } log.info("*** Repository initialized ***"); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } if (Config.USER_ITEM_CACHE) { // Deserialize try { log.info("*** Cache deserialization ***"); UserItemsManager.deserialize(); UserNodeKeywordsManager.deserialize(); } catch (DatabaseException e) { log.warn(e.getMessage(), e); } } log.info("*** User database initialized ***"); if (!Config.REPOSITORY_NATIVE) { // Test for datastore SessionImpl si = (SessionImpl) JcrRepositoryModule.getSystemSession(); if (((RepositoryImpl) si.getRepository()).getDataStore() == null) { hasConfiguredDataStore = false; } else { hasConfiguredDataStore = true; } } // Create timers uiTimer = new Timer("Update Info", true); cronTimer = new Timer("Crontab Manager", true); uinTimer = new Timer("User Interface Notification", true); // Workflow log.info("*** Initializing workflow engine... ***"); JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext(); jbpmContext.setSessionFactory(HibernateUtil.getSessionFactory()); jbpmContext.getGraphSession(); jbpmContext.getJbpmConfiguration().getJobExecutor().start(); // startJobExecutor(); jbpmContext.close(); // Mime types log.info("*** Initializing MIME types... ***"); MimeTypeConfig.loadMimeTypes(); if (Config.UPDATE_INFO) { log.info("*** Activating update info ***"); ui = new UpdateInfo(); uiTimer.schedule(ui, 1000, 24 * 60 * 60 * 1000); // First in 1 seg, next each 24 hours } log.info("*** Activating cron ***"); cron = new Cron(); Calendar calCron = Calendar.getInstance(); calCron.add(Calendar.MINUTE, 1); calCron.set(Calendar.SECOND, 0); calCron.set(Calendar.MILLISECOND, 0); // Round begin to next minute, 0 seconds, 0 miliseconds cronTimer.scheduleAtFixedRate(cron, calCron.getTime(), 60 * 1000); // First in 1 min, next each 1 min log.info("*** Activating UI Notification ***"); uin = new UINotification(); //Licensing stuff if (Config.HIBERNATE_HBM2DDL.equals("create")) { if (!LICENSE_PATH.exists()) { try { FileUtils.writeStringToFile(LICENSE_PATH, new DateTime().plusDays(30).toString(DateTimeFormat.forPattern("d MMM yyyy"))); } catch (IOException e) { e.printStackTrace(); } } } // First in 1 second next in x minutes uinTimer.scheduleAtFixedRate(uin, 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_UI_NOTIFICATION)); try { // General maintenance works String uisContent = "com.ikon.cache.UserItemsManager.serialize();"; CronTabUtils.createOrUpdate("User Items Serialize", "@hourly", uisContent); String umiContent = "new com.ikon.core.UserMailImporter().run();"; CronTabUtils.createOrUpdate("User Mail Importer", "*/30 * * * *", umiContent); String tewContent = "new com.ikon.extractor.TextExtractorWorker().run();"; CronTabUtils.createOrUpdate("Text Extractor Worker", "*/5 * * * *", tewContent); String riContent = "new com.ikon.core.RepositoryInfo().run();"; CronTabUtils.createOrUpdate("Repository Info", "@daily", riContent); String swdContent = "new com.ikon.core.Watchdog().run();"; CronTabUtils.createOrUpdate("Session Watchdog", "*/5 * * * *", swdContent); if (LicenseManager.getInstance().getFeature("Retention").equals("RET761WER")) { String retentionContent = "new com.ikon.util.RetentionPolicyTimer().run();"; CronTabUtils.createOrUpdate("Retention Policies", "* */10 * * *", retentionContent); } String hotFolderContent = "new com.ikon.util.HotFolderTimer().run();"; CronTabUtils.createOrUpdate("Hot Folders", "* */10 * * *", hotFolderContent); // Datastore garbage collection if (!Config.REPOSITORY_NATIVE && hasConfiguredDataStore) { String dgcContent = "new com.ikon.module.jcr.stuff.DataStoreGarbageCollector().run();"; CronTabUtils.createOrUpdate("Datastore Garbage Collector", "@daily", dgcContent); } } catch (Exception e) { log.warn(e.getMessage(), e); } try { log.info("*** Activating thesaurus repository ***"); RDFREpository.getInstance(); } catch (Exception e) { log.warn(e.getMessage(), e); } try { if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) { log.info("*** Start OpenOffice manager ***"); DocConverter.getInstance().start(); } else { log.warn("*** No OpenOffice manager configured ***"); } } catch (Throwable e) { log.warn(e.getMessage(), e); } // Initialize plugin framework ExtensionManager.getInstance(); try { log.info("*** Ejecute start script ***"); File script = new File(Config.HOME_DIR + File.separatorChar + Config.START_SCRIPT); ExecutionUtils.runScript(script); File jar = new File(Config.HOME_DIR + File.separatorChar + Config.START_JAR); ExecutionUtils.getInstance().runJar(jar); } catch (Throwable e) { log.warn(e.getMessage(), e); } // openkm is started running = true; }