/** * Adjusts adaptive poll frequency. * * @param pollInterval poll frequency in seconds */ synchronized void adjustCalAndPollInterval(int pollInterval) { initMemberVars(pollInterval); if (calAndShortFlowsThread != null) { calAndShortFlowsThread.cancel(false); } if (midFlowsThread != null) { midFlowsThread.cancel(false); } if (longFlowsThread != null) { longFlowsThread.cancel(false); } calAndShortFlowsTask = new CalAndShortFlowsTask(); calAndShortFlowsThread = adaptiveFlowStatsScheduler.scheduleWithFixedDelay( calAndShortFlowsTask, 0, calAndPollInterval, TimeUnit.SECONDS); midFlowsTask = new MidFlowsTask(); midFlowsThread = adaptiveFlowStatsScheduler.scheduleWithFixedDelay( midFlowsTask, 0, midPollInterval, TimeUnit.SECONDS); longFlowsTask = new LongFlowsTask(); longFlowsThread = adaptiveFlowStatsScheduler.scheduleWithFixedDelay( longFlowsTask, 0, longPollInterval, TimeUnit.SECONDS); log.debug("calAndPollInterval=" + calAndPollInterval + "is adjusted"); }
@Override public void contextInitialized(ServletContextEvent arg0) { smsCreatorScheduler = Executors.newSingleThreadScheduledExecutor(); smsCreatorScheduler.scheduleWithFixedDelay( new SmsCreatorThread(), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_SMS_CREATORL_INIT_DELAY)), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_SMS_CREATOR_PROC_DELAY)), TimeUnit.SECONDS); schedulerLogging.info("smsCreatorScheduler : startup context"); smsSenderScheduler = Executors.newSingleThreadScheduledExecutor(); smsSenderScheduler.scheduleWithFixedDelay( new SmsSenderThread(), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_SMS_SENDER_INIT_DELAY)), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_SMS_SENDER_PROC_DELAY)), TimeUnit.MINUTES); schedulerLogging.info("smsSenderScheduler : startup context"); mailScheduler = Executors.newSingleThreadScheduledExecutor(); mailScheduler.scheduleWithFixedDelay( new SingleMailmanThread(), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_STANNDARD_MAIL_INIT_DELAY)), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_STANNDARD_MAIL_PROC_DELAY)), TimeUnit.SECONDS); schedulerLogging.info("mailScheduler : startup context"); mailCreator = Executors.newSingleThreadScheduledExecutor(); mailCreator.scheduleWithFixedDelay( new EmailCreatorThread(), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_EMAIL_CREATORL_INIT_DELAY)), ParseUtil.sToL(processSchedulerConfig.get(Constants.PROP_EMAIL_CREATOR_PROC_DELAY)), TimeUnit.SECONDS); schedulerLogging.info("mailCreator : startup context"); }
public static void startSystem() throws ExecutionException, InterruptedException { // Create the entry gates and link them to the parking lot for (int i = 0; i < numOfEntries; i++) { entries.add(new Entry("entry" + i, parkingLot)); } parkingLot.setEntries(entries); // Create the exit gates and link them to the parking lot for (int k = 0; k < numOfExits; k++) { exits.add(new Exit("exit" + k, parkingLot)); } parkingLot.setExits(exits); // Create a thread pool based on the number of entries and exits for this lot ScheduledExecutorService scheduledExecutorService1 = Executors.newScheduledThreadPool(numOfEntries); ScheduledExecutorService scheduledExecutorService2 = Executors.newScheduledThreadPool(numOfExits); // Schedule the threads, which will act as Car objects entering and exiting the parking lot ScheduledFuture<?> scheduledFuture1 = scheduledExecutorService1.scheduleWithFixedDelay( new Car(entries, exits, 0), firstCarEntryTime, enteringCarsDelay, TimeUnit.SECONDS); ScheduledFuture<?> scheduledFuture2 = scheduledExecutorService2.scheduleWithFixedDelay( new Car(entries, exits, 1), firstCarExitTime, exitingCarsDelay, TimeUnit.SECONDS); scheduledFuture1.get(); scheduledFuture2.get(); scheduledExecutorService1.shutdown(); scheduledExecutorService2.shutdown(); }
private StatsCollector(Map<String, String> configs) { ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); _agentMgr = locator.getManager(AgentManager.class); _userVmMgr = locator.getManager(UserVmManager.class); _hostDao = locator.getDao(HostDao.class); _userVmDao = locator.getDao(UserVmDao.class); _volsDao = locator.getDao(VolumeDao.class); _capacityDao = locator.getDao(CapacityDao.class); _storagePoolDao = locator.getDao(StoragePoolDao.class); _storageManager = locator.getManager(StorageManager.class); _storagePoolHostDao = locator.getDao(StoragePoolHostDao.class); _executor = Executors.newScheduledThreadPool(3, new NamedThreadFactory("StatsCollector")); hostStatsInterval = NumbersUtil.parseLong(configs.get("host.stats.interval"), 60000L); hostAndVmStatsInterval = NumbersUtil.parseLong(configs.get("vm.stats.interval"), 60000L); storageStatsInterval = NumbersUtil.parseLong(configs.get("storage.stats.interval"), 60000L); volumeStatsInterval = NumbersUtil.parseLong(configs.get("volume.stats.interval"), -1L); _executor.scheduleWithFixedDelay( new HostCollector(), 15000L, hostStatsInterval, TimeUnit.MILLISECONDS); _executor.scheduleWithFixedDelay( new VmStatsCollector(), 15000L, hostAndVmStatsInterval, TimeUnit.MILLISECONDS); _executor.scheduleWithFixedDelay( new StorageCollector(), 15000L, storageStatsInterval, TimeUnit.MILLISECONDS); // -1 means we don't even start this thread to pick up any data. if (volumeStatsInterval > 0) { _executor.scheduleWithFixedDelay( new VolumeCollector(), 15000L, volumeStatsInterval, TimeUnit.MILLISECONDS); } else { s_logger.info("Disabling volume stats collector"); } }
/** start adaptive flow statistic collection. */ public synchronized void start() { log.debug("Starting AdaptiveStats collection thread for {}", sw.getStringId()); callCountCalAndShortFlowsTask = 0; callCountMidFlowsTask = 0; callCountLongFlowsTask = 0; isFirstTimeStart = true; // Initially start polling quickly. Then drop down to configured value calAndShortFlowsTask = new CalAndShortFlowsTask(); calAndShortFlowsThread = adaptiveFlowStatsScheduler.scheduleWithFixedDelay( calAndShortFlowsTask, 1, calAndPollInterval, TimeUnit.SECONDS); midFlowsTask = new MidFlowsTask(); midFlowsThread = adaptiveFlowStatsScheduler.scheduleWithFixedDelay( midFlowsTask, 1, midPollInterval, TimeUnit.SECONDS); longFlowsTask = new LongFlowsTask(); longFlowsThread = adaptiveFlowStatsScheduler.scheduleWithFixedDelay( longFlowsTask, 1, longPollInterval, TimeUnit.SECONDS); log.info("Started"); }
public void startTheJob() { final Runnable controllerEventsBatchProcessor = this::publishControllerPendingEvents; final Runnable ciEventsBatchProcessor = this::publishCIPendingEvents; jobHandle = controllerEventScheduler.scheduleWithFixedDelay( controllerEventsBatchProcessor, 0, 3, SECONDS); ciEventsJobHandle = ciEventScheduler.scheduleWithFixedDelay(ciEventsBatchProcessor, 0, 3, SECONDS); }
public void run() throws Exception { for (Thread t : searcherThreads) { t.start(); } for (Thread t : writerThreads) { t.start(); } barrier1.await(); Refresher refresher = new Refresher(); scheduledExecutorService.scheduleWithFixedDelay( refresher, refreshSchedule.millis(), refreshSchedule.millis(), TimeUnit.MILLISECONDS); Flusher flusher = new Flusher(); scheduledExecutorService.scheduleWithFixedDelay( flusher, flushSchedule.millis(), flushSchedule.millis(), TimeUnit.MILLISECONDS); StopWatch stopWatch = new StopWatch(); stopWatch.start(); barrier2.await(); latch.await(); stopWatch.stop(); System.out.println("Summary"); System.out.println( " -- Readers [" + searcherThreads.length + "] with [" + searcherIterations + "] iterations"); System.out.println( " -- Writers [" + writerThreads.length + "] with [" + writerIterations + "] iterations"); System.out.println(" -- Took: " + stopWatch.totalTime()); System.out.println( " -- Refresh [" + refresher.id + "] took: " + refresher.stopWatch.totalTime()); System.out.println(" -- Flush [" + flusher.id + "] took: " + flusher.stopWatch.totalTime()); System.out.println(" -- Store size " + store.estimateSize()); scheduledExecutorService.shutdown(); engine.refresh(new Engine.Refresh(true)); stopWatch = new StopWatch(); stopWatch.start(); Engine.Searcher searcher = engine.searcher(); TopDocs topDocs = searcher.searcher().search(new MatchAllDocsQuery(), idGenerator.get() + 1); stopWatch.stop(); System.out.println( " -- Indexed [" + idGenerator.get() + "] docs, found [" + topDocs.totalHits + "] hits, took " + stopWatch.totalTime()); searcher.release(); }
// Start moving the BubbleView & updating the display private void start() { // Creates a WorkerThread ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // Execute the run() in Worker Thread every REFRESH_RATE // milliseconds // Save reference to this job in mMoverFuture mMoverFuture = executor.scheduleWithFixedDelay( new Runnable() { @Override public void run() { // implement movement logic. // Each time this method is run the BubbleView should // move one step. If the BubbleView exits the display, // stop the BubbleView's Worker Thread. // Otherwise, request that the BubbleView be redrawn. boolean exits = moveWhileOnScreen(); if (exits) { stop(false); } else { BubbleView.this.postInvalidate(); } } }, 0, REFRESH_RATE, TimeUnit.MILLISECONDS); }
/** * DOCUMENT ME! * * @param watchable rootResource DOCUMENT ME! */ public void submit(final Watchable watchable) { final Deregister deregister = new Deregister(); final Runnable poll = new Poll(deregister, watchable); final ScheduledFuture future = poller.scheduleWithFixedDelay(poll, 30, 30, TimeUnit.SECONDS); deregister.self = future; }
@Activate public void activate(ComponentContext context) { configService.registerProperties(getClass()); idGenerator = coreService.getIdGenerator(FlowRuleService.FLOW_OP_TOPIC); local = clusterService.getLocalNode().id(); messageHandlingExecutor = Executors.newFixedThreadPool( msgHandlerPoolSize, groupedThreads("onos/store/flow", "message-handlers")); registerMessageHandlers(messageHandlingExecutor); if (backupEnabled) { replicaInfoManager.addListener(flowTable); backupTask = backupSenderExecutor.scheduleWithFixedDelay( flowTable::backup, 0, backupPeriod, TimeUnit.MILLISECONDS); } deviceTableStats = storageService .<DeviceId, List<TableStatisticsEntry>>eventuallyConsistentMapBuilder() .withName("onos-flow-table-stats") .withSerializer(SERIALIZER_BUILDER) .withAntiEntropyPeriod(5, TimeUnit.SECONDS) .withTimestampProvider((k, v) -> new WallClockTimestamp()) .withTombstonesDisabled() .build(); deviceTableStats.addListener(tableStatsListener); logConfig("Started"); }
/** @param defaultExpiration the TTL for objects in the cache in milliseconds */ public ExpiringMap(long defaultExpiration, final Function<Pair<K, V>, ?> postExpireHook) { this.defaultExpiration = defaultExpiration; if (defaultExpiration <= 0) { throw new IllegalArgumentException("Argument specified must be a positive number"); } Runnable runnable = new Runnable() { public void run() { long start = System.currentTimeMillis(); int n = 0; for (Map.Entry<K, CacheableObject<V>> entry : cache.entrySet()) { if (entry.getValue().isReadyToDieAt(start)) { cache.remove(entry.getKey()); n++; if (postExpireHook != null) postExpireHook.apply(new Pair<K, V>(entry.getKey(), entry.getValue().getValue())); } } logger.trace("Expired {} entries", n); } }; service.scheduleWithFixedDelay( runnable, defaultExpiration / 2, defaultExpiration / 2, TimeUnit.MILLISECONDS); }
@SuppressWarnings({"rawtypes", "unchecked"}) public void testMonitorAndContinueWithoutTimeout() { ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); expect( schedulerMock.scheduleWithFixedDelay( anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class))) .andReturn(mockFuture); replay(mockFuture); replay(schedulerMock); CoutingEventHandler handler = new CoutingEventHandler(); EventBus eventBus = new EventBus(); eventBus.register(handler); AsyncMonitor<Object> monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), eventBus); assertNull(monitor.getFuture()); assertNull(monitor.getTimeout()); monitor.startMonitoring(null); assertNotNull(monitor.getFuture()); assertNull(monitor.getTimeout()); monitor.run(); assertEquals(handler.numCompletes, 0); assertEquals(handler.numFailures, 0); assertEquals(handler.numTimeouts, 0); verify(mockFuture); verify(schedulerMock); }
@SuppressWarnings({"rawtypes", "unchecked"}) public void testStartMonitoringWithTimeout() { ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); expect( schedulerMock.scheduleWithFixedDelay( anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class))) .andReturn(mockFuture); replay(mockFuture); replay(schedulerMock); AsyncMonitor<Object> monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), new EventBus()); assertNull(monitor.getFuture()); assertNull(monitor.getTimeout()); monitor.startMonitoring(100L); assertNotNull(monitor.getFuture()); assertNotNull(monitor.getTimeout()); assertTrue(monitor.getTimeout() > 100L); verify(mockFuture); verify(schedulerMock); }
@Override public void start() { logger.info("Starting {}...", this); Responder responder = new SpecificResponder(AvroSourceProtocol.class, this); if (maxThreads <= 0) { server = new NettyServer(responder, new InetSocketAddress(bindAddress, port)); } else { server = new NettyServer( responder, new InetSocketAddress(bindAddress, port), new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newFixedThreadPool(maxThreads))); } connectionCountUpdater = Executors.newSingleThreadScheduledExecutor(); server.start(); sourceCounter.start(); super.start(); final NettyServer srv = (NettyServer) server; connectionCountUpdater.scheduleWithFixedDelay( new Runnable() { @Override public void run() { sourceCounter.setOpenConnectionCount(Long.valueOf(srv.getNumActiveConnections())); } }, 0, 60, TimeUnit.SECONDS); logger.info("Avro source {} started.", getName()); }
protected final void scrollBy(float velocityY) { cancelFuture(); mFuture = mExecutor.scheduleWithFixedDelay( new InertiaTimerTask(this, velocityY), 0, VELOCITYFLING, TimeUnit.MILLISECONDS); }
{ ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); updateDetectorFuture = executor.scheduleWithFixedDelay( new StatusUpdateDetector(), 5, POLL_PERIOD, TimeUnit.SECONDS); }
public synchronized void startIndexing() { stopIndexing(); // stop executors if they are already running, otherwise they will never stop if (registryConfig.IsStartIndexing()) { submittingExecutor = Executors.newSingleThreadScheduledExecutor(); submittingExecutor.scheduleWithFixedDelay( new ResourceSubmitter(this), getStartingDelayInSecs(), getIndexingFreqInSecs(), TimeUnit.SECONDS); indexingExecutor = Executors.newSingleThreadScheduledExecutor(); indexingExecutor.scheduleWithFixedDelay( indexer, getStartingDelayInSecs(), getIndexingFreqInSecs(), TimeUnit.SECONDS); readLastAccessTime(); } }
public static void main(String[] args) throws Exception { BasicConfigurator.configure(); String username = "******"; final String TWITTER_OAUTH_KEY = ""; final String TWITTER_OAUTH_SECRET = ""; final String ACCESS_TOKEN = ""; final String ACCESS_TOKEN_SECRET = ""; OAuthSignpostClient oauth = new OAuthSignpostClient( TWITTER_OAUTH_KEY, TWITTER_OAUTH_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET); TwitterClient twitter = new TwitterClient(username, oauth); Connection conn = DriverManager.getConnection("jdbc:postgresql://juergenbickert.de:5432/smsd?user=smsd"); conn.setAutoCommit(false); conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); SmsProvider smsProvider = new SmsProvider(conn); TwitterTask task = new TwitterTask(twitter, smsProvider); task.setAppend(" #tmn12"); ScheduledExecutorService pool = Executors.newScheduledThreadPool(1); pool.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); }
/** * Submits or schedules an {@link ApplicationTask} on the the shared executor service. * * @param task The task * @param delay Initial delay in milliseconds, or zero for ASAP * @param repeatEvery Repeat delay in milliseconds, or zero for no repetition * @param fixedRepeat Whether repetitions are at fixed times, or if the repeat delay begins when * the task ends * @return A future for the task */ private <T> Future<T> task( ApplicationTask<T> task, int delay, int repeatEvery, boolean fixedRepeat) { ExecutorService executor = getExecutor(); if ((delay > 0) || (repeatEvery > 0)) { if (!(executor instanceof ScheduledExecutorService)) throw new RuntimeException( "Executor must implement the ScheduledExecutorService interface to allow for delayed tasks"); ScheduledExecutorService scheduledExecutor = (ScheduledExecutorService) executor; if (repeatEvery > 0) { if (fixedRepeat) { @SuppressWarnings("unchecked") ScheduledFuture<T> future = (ScheduledFuture<T>) scheduledExecutor.scheduleAtFixedRate( task, delay, repeatEvery, TimeUnit.MILLISECONDS); return future; } else { @SuppressWarnings("unchecked") ScheduledFuture<T> future = (ScheduledFuture<T>) scheduledExecutor.scheduleWithFixedDelay( task, delay, repeatEvery, TimeUnit.MILLISECONDS); return future; } } else return scheduledExecutor.schedule((Callable<T>) task, delay, TimeUnit.MILLISECONDS); } else return executor.submit((Callable<T>) task); }
void startBackgroundInvalidate() { if (isScheduled.get()) { throw new IllegalStateException("already scheduled"); } if (!isScheduled.compareAndSet(false, true)) { throw new IllegalStateException("already scheduled"); } taskExecutor = Executors.newScheduledThreadPool( config.getInvalidateThreads(), new NameableDaemonThreadFactory(AsyncInvalidateThread.class.getSimpleName())); InvalidateTaskBootstrap bootstrap = new InvalidateTaskBootstrap(); taskExecutor.scheduleWithFixedDelay( bootstrap, config.getInvalidateThreadInitialDelayMillis(), config.getInvalidateIntervalMillis(), TimeUnit.MILLISECONDS); Runtime.getRuntime() .addShutdownHook( new Thread( new Runnable() { @Override public void run() { taskExecutor.shutdownNow(); } })); }
public Shutdown start( final Builder builder, final int intervalMillis, final int repetitions, final AutomaticFuture automaticFuture) { synchronized (this) { if (shutdown) { return new Shutdown() { @Override public BaseFuture shutdown() { return new FutureDone<Void>().done(); } }; } final CountDownLatch latch = new CountDownLatch(1); final DirectReplicationWorker worker = new DirectReplicationWorker(builder, automaticFuture, repetitions, latch); ScheduledFuture<?> future = scheduledExecutorService.scheduleWithFixedDelay( worker, 0, intervalMillis, TimeUnit.MILLISECONDS); worker.future = future; latch.countDown(); return new Shutdown() { @Override public BaseFuture shutdown() { worker.shutdown(); return new FutureDone<Void>().done(); } }; } }
public JobLoggerDelegate(Config config) { JobLoggerFactory jobLoggerFactory = ExtensionLoader.getExtensionLoader(JobLoggerFactory.class).getAdaptiveExtension(); jobLogger = jobLoggerFactory.getJobLogger(config); lazyLog = config.getParameter(Constants.LAZY_JOB_LOGGER, false); if (lazyLog) { // 无界Queue memoryQueue = new LinkedBlockingQueue<JobLogPo>(); maxMemoryLogSize = config.getParameter(Constants.LAZY_JOB_LOGGER_MEM_SIZE, 1000); flushPeriod = config.getParameter(Constants.LAZY_JOB_LOGGER_CHECK_PERIOD, 3); executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("LazyJobLogger")); scheduledFuture = executor.scheduleWithFixedDelay( new Runnable() { @Override public void run() { try { if (flushing.compareAndSet(false, true)) { checkAndFlush(); } } catch (Throwable t) { LOGGER.error("CheckAndFlush log error", t); } } }, flushPeriod, flushPeriod, TimeUnit.SECONDS); } }
private void _initCommitScheduler() { if ((PropsValues.LUCENE_COMMIT_BATCH_SIZE <= 0) || (PropsValues.LUCENE_COMMIT_TIME_INTERVAL <= 0)) { return; } ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); Runnable runnable = new Runnable() { @Override public void run() { try { if (_batchCount > 0) { _doCommit(); } } catch (IOException ioe) { _log.error("Could not run scheduled commit", ioe); } } }; scheduledExecutorService.scheduleWithFixedDelay( runnable, 0, PropsValues.LUCENE_COMMIT_TIME_INTERVAL, TimeUnit.MILLISECONDS); }
/** * Create the structure to enable submission by database * * @throws WaarpDatabaseNoConnectionException * @throws WaarpDatabaseSqlException */ public InternalRunner() throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { if (DbConstant.admin.isActive()) { commander = new Commander(this, true); } else { commander = new CommanderNoDb(this, true); } scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new WaarpThreadFactory("InternalRunner")); isRunning = true; BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(10); threadPoolExecutor = new ThreadPoolExecutor( 10, Configuration.configuration.getRUNNER_THREAD(), 1000, TimeUnit.MILLISECONDS, workQueue); scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay( commander, Configuration.configuration.getDelayCommander(), Configuration.configuration.getDelayCommander(), TimeUnit.MILLISECONDS); networkTransaction = new NetworkTransaction(); }
@Override public void init() { super.init(); eventBus = new EventBus(this); eventBus.addRegistrationListener( new ResourceRegistrationListener() { @Override public void resourceUnregistered(String uuid) { System.out.println("Unregistered " + uuid); } @Override public void resourceRegistered(String uuid, Page page) { System.out.println("Registered " + uuid); } }); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final Runnable beeper = new Runnable() { @Override public void run() { try { eventBus.post(new Date()); } catch (Exception e) { e.printStackTrace(); } } }; scheduler.scheduleWithFixedDelay(beeper, 2, 2, TimeUnit.SECONDS); }
public void run() { while (true) { try { ThEvent event = queue.take(); // 获取并移除此队列的头,如果此队列为空,则返回 null。 size++; process(event); long curTime = System.currentTimeMillis(); if (size == batchSize || ((curTime - lastTime) > batchTime)) { int temp = size; if (temp > 0) { size = 0; if (flag) { ScheduledExecutorService service = Executors.newScheduledThreadPool(1); Runnable hbase = new HbaseStorageTask(hbaseService.getTable(), "event"); // hbase.run(); // 首次启动初始化缓存 service.scheduleWithFixedDelay(hbase, 1, 10, TimeUnit.SECONDS); flag = false; } } log.info( "批量存储驾驶事件数据信息----提交:[{}]条, 耗时:[{}]ms", temp, (System.currentTimeMillis() - lastTime)); lastTime = System.currentTimeMillis(); } } catch (Exception e) { log.error("存储驾驶事件数据异常:" + e.getMessage(), e); } } }
public AbstractRedisRegistry(URL url) { super(url); RedisRegistryUtil.assertNotAnyHost(url); GenericObjectPoolConfig config = RedisRegistryUtil.genericObjectPoolConfig(url); List<String> addresses = RedisRegistryUtil.getAddresses(url); for (String address : addresses) { JedisPool jedisPool = RedisRegistryUtil.initJedisPoolAndCheck(url, config, address); jedisPools.put(address, jedisPool); } this.replicate = RedisRegistryUtil.getReplicate(url); this.reconnectPeriod = url.getParameter( Constants.REGISTRY_RECONNECT_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD); this.root = RedisRegistryUtil.getGroup(url); this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT); this.expireFuture = expireExecutor.scheduleWithFixedDelay( new Runnable() { public void run() { try { deferExpired(); // 延长过期时间 } catch (Throwable t) { // 防御性容错 logger.error( "Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t); } } }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS); }
public void start() throws Exception { if (!isStarted()) { LOG.info("Starting server Plugin Registry..."); scheduledExecutor = Executors.newScheduledThreadPool(2, new KEWThreadFactory()); sharedPluginDirectory = loadSharedPlugin(); reloader = new Reloader(); hotDeployer = new HotDeployer(this, sharedPluginDirectory, pluginDirectories); loadPlugins(sharedPluginDirectory); this.reloaderFuture = scheduledExecutor.scheduleWithFixedDelay(reloader, 5, 5, TimeUnit.SECONDS); this.hotDeployerFuture = scheduledExecutor.scheduleWithFixedDelay(hotDeployer, 5, 5, TimeUnit.SECONDS); super.start(); LOG.info("...server Plugin Registry successfully started."); } }
// Start moving the BubbleView & updating the display private void startMovement() { // Creates a WorkerThread ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // Execute the run() in Worker Thread every REFRESH_RATE // milliseconds // Save reference to this job in mMoverFuture mMoverFuture = executor.scheduleWithFixedDelay( new Runnable() { @Override public void run() { // Each time this method is run the BubbleView should // move one step. If the BubbleView exits the display, // stop the BubbleView's Worker Thread. // Otherwise, request that the BubbleView be redrawn. while (moveWhileOnScreen()) { postInvalidate(); try { Thread.sleep(1000); } catch (InterruptedException e) { mFrame.removeView(BubbleView.this); } } stopMovement(false); } }, 0, REFRESH_RATE, TimeUnit.MILLISECONDS); }
@Test public void testClientInactivity() throws Exception { long maxInactivityPeriod = 4000; bayeux.addExtension( new ActivityExtension(ActivityExtension.Activity.CLIENT, maxInactivityPeriod)); scheduler.scheduleWithFixedDelay( new Runnable() { public void run() { bayeux.getChannel(channelName).publish(null, "test"); } }, 0, timeout / 4, TimeUnit.MILLISECONDS); final BayeuxClient client = newBayeuxClient(); client .getChannel(Channel.META_HANDSHAKE) .addListener( new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { if (message.isSuccessful()) { client .getChannel(channelName) .subscribe( new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) {} }); } } }); final CountDownLatch latch = new CountDownLatch(2); client .getChannel(Channel.META_CONNECT) .addListener( new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { Map<String, Object> advice = message.getAdvice(); if (advice != null && Message.RECONNECT_NONE_VALUE.equals(advice.get(Message.RECONNECT_FIELD))) { latch.countDown(); } } }); client .getChannel(Channel.META_DISCONNECT) .addListener( new ClientSessionChannel.MessageListener() { public void onMessage(ClientSessionChannel channel, Message message) { latch.countDown(); } }); client.handshake(); Assert.assertTrue(latch.await(2 * maxInactivityPeriod, TimeUnit.MILLISECONDS)); }