List of usage examples for java.util.concurrent ScheduledExecutorService scheduleWithFixedDelay
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
From source file:org.usergrid.persistence.cassandra.CassandraService.java
public void startClusterHealthCheck() { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(new Runnable() { @Override// ww w .ja v a 2 s . c o m public void run() { if (cluster != null) { HConnectionManager connectionManager = cluster.getConnectionManager(); if (connectionManager != null) { clusterUp = !connectionManager.getHosts().isEmpty(); } } } }, 1, 5, TimeUnit.SECONDS); }
From source file:com.comcast.cqs.test.stress.CqsStressTester.java
private ScheduledExecutorService createSenders(List<String> queueUrls) { int senderCount = CQSStressTestProperties.getInstance().getNumberOfSendersPerQueue(); if (senderCount == 0) { return null; }/*from w ww. jav a2 s .c o m*/ int numberOfMessagesPerSec = CQSStressTestProperties.getInstance().getMessagesPerQueuePerSecond(); ScheduledExecutorService scheduledExecutorService = Executors .newScheduledThreadPool(queueUrls.size() * senderCount); for (String queueUrl : queueUrls) { for (int i = 0; i < senderCount; i++) { scheduledExecutorService.scheduleWithFixedDelay(new MessageSender(queueUrl, i), rand.nextInt(100), 1000 * senderCount / numberOfMessagesPerSec, TimeUnit.MILLISECONDS); } } return scheduledExecutorService; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.dns.ZoneManager.java
protected static void initZoneCache(final TrafficRouter tr) { synchronized (ZoneManager.class) { final CacheRegister cacheRegister = tr.getCacheRegister(); final JSONObject config = cacheRegister.getConfig(); int poolSize = 1; final double scale = config.optDouble("zonemanager.threadpool.scale", 0.75); final int cores = Runtime.getRuntime().availableProcessors(); if (cores > 2) { final Double s = Math.floor((double) cores * scale); if (s.intValue() > 1) { poolSize = s.intValue(); }/*from ww w . jav a2 s . c o m*/ } final ExecutorService initExecutor = Executors.newFixedThreadPool(poolSize); final ExecutorService ze = Executors.newFixedThreadPool(poolSize); final ScheduledExecutorService me = Executors.newScheduledThreadPool(2); // 2 threads, one for static, one for dynamic, threads to refresh zones final int maintenanceInterval = config.optInt("zonemanager.cache.maintenance.interval", 300); // default 5 minutes final String dspec = "expireAfterAccess=" + config.optString("zonemanager.dynamic.response.expiration", "300s"); // default to 5 minutes final LoadingCache<ZoneKey, Zone> dzc = createZoneCache(ZoneCacheType.DYNAMIC, CacheBuilderSpec.parse(dspec)); final LoadingCache<ZoneKey, Zone> zc = createZoneCache(ZoneCacheType.STATIC); initZoneDirectory(); try { LOGGER.info("Generating zone data"); generateZones(tr, zc, dzc, initExecutor); initExecutor.shutdown(); initExecutor.awaitTermination(5, TimeUnit.MINUTES); LOGGER.info("Zone generation complete"); } catch (final InterruptedException ex) { LOGGER.warn("Initialization of zone data exceeded time limit of 5 minutes; continuing", ex); } catch (IOException ex) { LOGGER.fatal("Caught fatal exception while generating zone data!", ex); } me.scheduleWithFixedDelay(getMaintenanceRunnable(dzc, ZoneCacheType.DYNAMIC, maintenanceInterval), 0, maintenanceInterval, TimeUnit.SECONDS); me.scheduleWithFixedDelay(getMaintenanceRunnable(zc, ZoneCacheType.STATIC, maintenanceInterval), 0, maintenanceInterval, TimeUnit.SECONDS); final ExecutorService tze = ZoneManager.zoneExecutor; final ScheduledExecutorService tme = ZoneManager.zoneMaintenanceExecutor; final LoadingCache<ZoneKey, Zone> tzc = ZoneManager.zoneCache; final LoadingCache<ZoneKey, Zone> tdzc = ZoneManager.dynamicZoneCache; ZoneManager.zoneExecutor = ze; ZoneManager.zoneMaintenanceExecutor = me; ZoneManager.dynamicZoneCache = dzc; ZoneManager.zoneCache = zc; if (tze != null) { tze.shutdownNow(); } if (tme != null) { tme.shutdownNow(); } if (tzc != null) { tzc.invalidateAll(); } if (tdzc != null) { tdzc.invalidateAll(); } } }
From source file:com.alibaba.cobar.client.datasources.ha.FailoverHotSwapDataSourceCreator.java
public DataSource createHADataSource(CobarDataSourceDescriptor descriptor) throws Exception { DataSource activeDataSource = descriptor.getTargetDataSource(); DataSource standbyDataSource = descriptor.getStandbyDataSource(); if (activeDataSource == null && standbyDataSource == null) { throw new IllegalArgumentException("must have at least one data source active."); }/*from w ww.j a v a 2s . c om*/ if (activeDataSource == null || standbyDataSource == null) { logger.warn("only one data source is available for use, so no HA support."); if (activeDataSource == null) { return standbyDataSource; } return activeDataSource; } HotSwappableTargetSource targetSource = new HotSwappableTargetSource(activeDataSource); ProxyFactory pf = new ProxyFactory(); pf.setInterfaces(new Class[] { DataSource.class }); pf.setTargetSource(targetSource); if (isPositiveFailoverEnable()) { DataSource targetDetectorDataSource = descriptor.getTargetDetectorDataSource(); DataSource standbyDetectorDataSource = descriptor.getStandbyDetectorDataSource(); if (targetDetectorDataSource == null || standbyDetectorDataSource == null) { throw new IllegalArgumentException( "targetDetectorDataSource or standbyDetectorDataSource can't be null if positive failover is enabled."); } // 1. create active monitoring job for failover event ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); ExecutorService jobExecutor = Executors.newFixedThreadPool(1); jobExecutorRegistry.add(jobExecutor); FailoverMonitorJob job = new FailoverMonitorJob(jobExecutor); // 1.1 inject dependencies job.setHotSwapTargetSource(targetSource); job.setMasterDataSource(activeDataSource); job.setStandbyDataSource(standbyDataSource); job.setMasterDetectorDataSource(targetDetectorDataSource); job.setStandbyDetectorDataSource(standbyDetectorDataSource); job.setCurrentDetectorDataSource(targetDetectorDataSource); job.setDetectingRequestTimeout(getDetectingTimeoutThreshold()); job.setDetectingSQL(getDetectingSql()); job.setRecheckInterval(recheckInterval); job.setRecheckTimes(recheckTimes); // 1.2 start scheduling and keep reference for canceling and shutdown ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(job, initialDelay, monitorPeriod, TimeUnit.MILLISECONDS); schedulerFutures.put(future, scheduler); } if (isPassiveFailoverEnable()) { // 2. create data source proxy with passive event advice PassiveEventHotSwappableAdvice advice = new PassiveEventHotSwappableAdvice(); advice.setRetryInterval(recheckInterval); advice.setRetryTimes(recheckTimes); advice.setDetectingSql(detectingSql); advice.setTargetSource(targetSource); advice.setMainDataSource(activeDataSource); advice.setStandbyDataSource(standbyDataSource); pf.addAdvice(advice); } return (DataSource) pf.getProxy(); }
From source file:cn.vko.cache.dao.ha.FailoverHotSwapDataSourceCreator.java
@Override public DataSource createHADataSource(DataSourceDescriptor descriptor) throws Exception { DataSource activeDataSource = descriptor.getTarget(); DataSource standbyDataSource = descriptor.getStandby(); if (activeDataSource == null && standbyDataSource == null) { throw new IllegalArgumentException("must have at least one data source active."); }//from www .j a v a2 s . c o m if (activeDataSource == null || standbyDataSource == null) { logger.warn("only one data source is available for use, so no HA support."); if (activeDataSource == null) { return standbyDataSource; } return activeDataSource; } HotSwappableTargetSource targetSource = new HotSwappableTargetSource(activeDataSource); ProxyFactory pf = new ProxyFactory(); pf.setInterfaces(new Class[] { DataSource.class }); pf.setTargetSource(targetSource); if (isPositiveFailoverEnable()) { DataSource targetDetectorDataSource = descriptor.getTarget(); DataSource standbyDetectorDataSource = descriptor.getStandby(); if (targetDetectorDataSource == null || standbyDetectorDataSource == null) { throw new IllegalArgumentException( "targetDetectorDataSource or standbyDetectorDataSource can't be null if positive failover is enabled."); } // 1. create active monitoring job for failover event ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); ExecutorService jobExecutor = Executors.newFixedThreadPool(1); jobExecutorRegistry.add(jobExecutor); FailoverMonitorJob job = new FailoverMonitorJob(jobExecutor); // 1.1 inject dependencies job.setHotSwapTargetSource(targetSource); job.setMasterDataSource(activeDataSource); job.setStandbyDataSource(standbyDataSource); job.setMasterDetectorDataSource(targetDetectorDataSource); job.setStandbyDetectorDataSource(standbyDetectorDataSource); job.setCurrentDetectorDataSource(targetDetectorDataSource); job.setDetectingRequestTimeout(getDetectingTimeoutThreshold()); job.setDetectingSQL(getDetectingSql()); job.setRecheckInterval(recheckInterval); job.setRecheckTimes(recheckTimes); // 1.2 start scheduling and keep reference for canceling and shutdown ScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(job, initialDelay, monitorPeriod, TimeUnit.MILLISECONDS); schedulerFutures.put(future, scheduler); } if (isPassiveFailoverEnable()) { // 2. create data source proxy with passive event advice PassiveEventHotSwappableAdvice advice = new PassiveEventHotSwappableAdvice(); advice.setRetryInterval(recheckInterval); advice.setRetryTimes(recheckTimes); advice.setDetectingSql(detectingSql); advice.setTargetSource(targetSource); advice.setMainDataSource(activeDataSource); advice.setStandbyDataSource(standbyDataSource); pf.addAdvice(advice); } return (DataSource) pf.getProxy(); }
From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java
@Override public void registerRegularPoll(@NonNull PollTask task, long pollPeriodMillis, long initialDelayMillis) { synchronized (this) { ScheduledExecutorService executor = scheduledThreadPoolExecutor; Objects.requireNonNull(executor, "Not activated!"); logger.trace("Registering poll task {} with period {} using initial delay {}", task, pollPeriodMillis, initialDelayMillis);/*from w w w . j ava 2 s .c o m*/ if (scheduledPollTasks.containsKey(task)) { logger.trace("Unregistering previous poll task (possibly with different period)"); unregisterRegularPoll(task); } ScheduledFuture<?> future = executor.scheduleWithFixedDelay(() -> { long started = System.currentTimeMillis(); logger.debug("Executing scheduled ({}ms) poll task {}. Current millis: {}", pollPeriodMillis, task, started); executeOperation(task, false, pollOperation); long finished = System.currentTimeMillis(); logger.debug( "Execution of scheduled ({}ms) poll task {} finished at {}. Was started at millis: {} (=duration of {} millis)", pollPeriodMillis, task, finished, started, finished - started); }, initialDelayMillis, pollPeriodMillis, TimeUnit.MILLISECONDS); scheduledPollTasks.put(task, future); logger.trace("Registered poll task {} with period {} using initial delay {}", task, pollPeriodMillis, initialDelayMillis); } }
From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java
@Activate protected void activate(Map<String, Object> configProperties) { synchronized (this) { logger.info("Modbus manager activated"); if (connectionPool == null) { constructConnectionPool();/* ww w . ja v a 2s . com*/ } ScheduledExecutorService scheduledThreadPoolExecutor = this.scheduledThreadPoolExecutor; if (scheduledThreadPoolExecutor == null) { this.scheduledThreadPoolExecutor = scheduledThreadPoolExecutor = ThreadPoolManager .getScheduledPool(MODBUS_POLLER_THREAD_POOL_NAME); } if (scheduledThreadPoolExecutor.isShutdown()) { logger.error("Thread pool is shut down! Aborting activation of ModbusMangerImpl"); throw new IllegalStateException( "Thread pool(s) shut down! Aborting activation of ModbusMangerImpl"); } monitorFuture = scheduledThreadPoolExecutor.scheduleWithFixedDelay(this::logTaskQueueInfo, 0, MONITOR_QUEUE_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } }
From source file:com.eviware.loadui.groovy.GroovyBehaviorProvider.java
public GroovyBehaviorProvider(ComponentRegistry registry, ScheduledExecutorService scheduler, File scriptDir, ClassLoaderRegistry clr) {// w w w . j a v a 2 s . co m if (!scriptDir.isAbsolute()) { scriptDir = LoadUI.relativeFile(scriptDir.getPath()); } this.scriptDir = scriptDir; this.registry = registry; this.clr = clr; File groovyRoot = new File(System.getProperty("groovy.root")); if (!groovyRoot.isDirectory()) if (!groovyRoot.mkdirs()) throw new RuntimeException( "Unable to create required directories: " + groovyRoot.getAbsolutePath()); File grapeConfig = new File(groovyRoot, "grapeConfig.xml"); if (!grapeConfig.exists()) { try { Files.copy(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return getClass().getResourceAsStream("/grapeConfig.xml"); } }, grapeConfig); } catch (IOException e) { e.printStackTrace(); } } // registry.registerDescriptor( emptyDescriptor, this ); registry.registerType(TYPE, this); future = scheduler.scheduleWithFixedDelay(new DirWatcher(), 0, UPDATE_FREQUENCY, TimeUnit.SECONDS); }
From source file:org.opennms.netmgt.provision.service.NodeScan.java
ScheduledFuture<?> schedule(ScheduledExecutorService executor, NodeScanSchedule schedule) { final Runnable r = new Runnable() { @Override/*from ww w .j a v a 2 s . co m*/ public void run() { try { final Task t = createTask(); t.schedule(); t.waitFor(); LOG.info("Finished scanning node {}/{}/{}", getNodeId(), getForeignSource(), getForeignId()); } catch (final InterruptedException e) { LOG.warn("The node scan for node {}/{}/{} was interrupted", getNodeId(), getForeignSource(), getForeignId(), e); Thread.currentThread().interrupt(); } catch (final ExecutionException e) { LOG.warn("An error occurred while scanning node {}/{}/{}", getNodeId(), getForeignSource(), getForeignId(), e); } } }; return executor.scheduleWithFixedDelay(r, schedule.getInitialDelay().getMillis(), schedule.getScanInterval().getMillis(), TimeUnit.MILLISECONDS); }
From source file:org.apache.jackrabbit.core.lock.LockManagerImpl.java
/** * Create a new instance of this class./*ww w. j a v a 2 s.com*/ * * @param session system session * @param fs file system for persisting locks * @param executor scheduled executor service for handling lock timeouts * @throws RepositoryException if an error occurs */ public LockManagerImpl(SessionImpl session, FileSystem fs, ScheduledExecutorService executor) throws RepositoryException { this.sysSession = session; this.locksFile = new FileSystemResource(fs, FileSystem.SEPARATOR + LOCKS_FILE); session.getWorkspace().getObservationManager().addEventListener(this, Event.NODE_ADDED | Event.NODE_REMOVED, "/", true, null, null, true); try { if (locksFile.exists()) { load(); } } catch (FileSystemException e) { throw new RepositoryException("I/O error while reading locks from '" + locksFile.getPath() + "'", e); } timeoutHandler = executor.scheduleWithFixedDelay(new TimeoutHandler(), 1, 1, TimeUnit.SECONDS); }