List of usage examples for java.util.concurrent Executors newScheduledThreadPool
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
From source file:org.tvheadend.tvhclient.htsp.HTSService.java
@Override public void onCreate() { execService = Executors.newScheduledThreadPool(5); prefs = PreferenceManager.getDefaultSharedPreferences(this); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); try {//w w w.ja v a 2 s .c om packInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException ex) { Log.e(TAG, "Can't get package info", ex); } }
From source file:org.apache.ambari.servicemonitor.jobs.BulkFileJobSubmitter.java
private int exec() throws Exception { CommandLine commandLine = getCommandLine(); Configuration conf = getConf(); String outputdir = OptionHelper.getStringOption(commandLine, "o", "bulkjob"); outputPath = new Path(outputdir); if (commandLine.hasOption('x')) { //delete the filesystem dir. This will deleteOutputDirectories = true;/*from w w w. j av a2 s . c o m*/ } jobs = OptionHelper.getIntOption(commandLine, "j", 1); int delay = OptionHelper.getIntOption(commandLine, "l", 1000); doneSignal = new CountDownLatch(jobs); templateConf = new JobConf(conf); String jtURI = MonitorUtils.extractJobTrackerParameter(templateConf); LOG.info("Submitting " + (jobs >= 0 ? jobs : "unlimited") + " jobs with a delay of " + delay + " millis" + " to JT " + jtURI + " and filesystem " + templateConf.get(FileSystem.FS_DEFAULT_NAME_KEY)); int jobCount = 0; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(POOL_SIZE); int toSubmit = jobs; long started, finished; started = System.currentTimeMillis(); while (toSubmit > 0) { scheduler.submit(new JobWorker("instance-" + (++jobCount))); Thread.sleep(delay); toSubmit--; } LOG.info("All jobs scheduled in local queue"); //here all the jobs are submitted, await their completion. doneSignal.await(); finished = System.currentTimeMillis(); int s = successes.get(); int f = failures.get(); long execDuration = totalExecDuration.get(); long elapsedTime = finished - started; LOG.info("Completed. Successes = " + s + " out of " + jobs + " success rate= " + (s * 100) / (jobs) + "% " + " total execTime " + MonitorUtils.millisToHumanTime(execDuration) + " " + " elapsed Time " + MonitorUtils.millisToHumanTime(elapsedTime)); return f == 0 ? 0 : 1; }
From source file:ezbake.discovery.stethoscope.server.StethoscopeServiceHandler.java
@Override public TProcessor getThriftProcessor() { this.configuration = new EzProperties(getConfigurationProperties(), true); this.serviceDiscoveryClient = new ServiceDiscoveryClient(configuration); int expireMinutes = configuration.getInteger(STETHOSCOPE_SERVICE_WRITE_EXPIRE_TIME, 15); boolean shouldRemoveEntriesFromZookeeper = configuration .getBoolean(STETHOSCOPE_ACTUALLY_REMOVE_FROM_ZOOKEEPER, false); logger.info("Stethoscope will wait {} minutes before timing something out after write", expireMinutes); Multimap<String, String> servicesToIgnore = getServicesToIgnore( configuration.getProperty(STETHOSCOPE_SERVICES_TO_IGNORE, "")); for (Map.Entry<String, String> entry : servicesToIgnore.entries()) { logger.info("Application: {}, Service: {} will NOT be removed from zookeeper", entry.getKey(), entry.getValue());// w w w.j a v a 2 s . c o m } if (shouldRemoveEntriesFromZookeeper) { logger.info("Stethoscope will remove entries from zookeeper"); } else { logger.info("Stethoscope will NOT remove entries from zookeeper"); } this.serviceCache = CacheBuilder.newBuilder().expireAfterWrite(expireMinutes, TimeUnit.MINUTES) .removalListener(new StethoscopeCacheRemovalListener(serviceDiscoveryClient, shouldRemoveEntriesFromZookeeper, servicesToIgnore)) .build(); this.scheduler = Executors.newScheduledThreadPool(1); int cleanupMinutes = configuration.getInteger(STETHOSCOPE_SERVICE_CLEANUP_TIME, 10); logger.info("Stethoscope will wait {} minutes before running the clean up thread!", cleanupMinutes); scheduler.scheduleAtFixedRate(new CacheMaintenanceRunnable(), 0, cleanupMinutes, TimeUnit.MINUTES); populateCacheFromZookeeper(); return new StethoscopeService.Processor(this); }
From source file:org.ebayopensource.scc.impl.DefaultPolicyManagerTest.java
@Test(expected = IllegalArgumentException.class) public void testJsonConfigWithInvalidJCSClassName() { String jsonConfig = "{" + "\"update\" : \"INVALID_ALG\"" + "}"; m_configMap.clear();/*from www . j a v a2 s .c o m*/ m_configMap.putAll(new Gson().fromJson(jsonConfig, Map.class)); new DefaultPolicyManager(m_appConfigMock, m_keyGenMock, Executors.newScheduledThreadPool(1)); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.distributed.NodeQueueLoadMonitor.java
public NodeQueueLoadMonitor(long nodeComputationInterval, LoadComparator comparator) { this.sortedNodes = new ArrayList<>(); this.scheduledExecutor = Executors.newScheduledThreadPool(1); this.comparator = comparator; this.scheduledExecutor.scheduleAtFixedRate(computeTask, nodeComputationInterval, nodeComputationInterval, TimeUnit.MILLISECONDS); }
From source file:org.jpos.space.HzlSpace.java
private void createSpace(String spaceName, String configFile) { if (configFile != null && !configFile.isEmpty()) { this.hzlConfigFile = configFile; } else {/*from www .j a va 2 s. c om*/ if (this.cfg != null) { this.hzlConfigFile = cfg.get("hzlConfigFile", ""); } } if (this.hzlConfigFile != null && !this.hzlConfigFile.isEmpty()) { try { this.hzlConfig = new XmlConfigBuilder(this.hzlConfigFile).build(); this.hzlConfig.setLiteMember(cfg.getBoolean("liteMember", false)); } catch (FileNotFoundException e) { throw new SpaceError(e); } } try { if (this.cfg != null && this.hzlConfig != null) { this.instance = Hazelcast.init(this.hzlConfig); } else { this.instance = Hazelcast.getDefaultInstance(); } } catch (Exception e) { e.printStackTrace(); } this.entries = this.instance.getMap(spaceName); this.expirables = this.instance.getList(spaceName + "-expirables"); this.expirables.add(new HashSet<K>()); this.expirables.add(new HashSet<K>()); this.cleanupScheduler = Executors.newScheduledThreadPool(1); }
From source file:org.aludratest.cloud.impl.app.CloudManagerApplicationHolder.java
private void internalStartup() throws PlexusContainerException, ComponentLookupException, ConfigException { plexus = new DefaultPlexusContainer(); saveScheduler = Executors.newScheduledThreadPool(1); application = plexus.lookup(CloudManagerApp.class); rootPreferences = new MainPreferencesImpl(null); ((MainPreferencesImpl) rootPreferences).applyPreferences(readConfig()); attachPreferencesListener(rootPreferences); String sDbPort = System.getProperty("derby.port", "1527"); Integer dbPort = null;/*ww w . jav a 2s . co m*/ if (sDbPort != null) { try { dbPort = Integer.valueOf(sDbPort); } catch (NumberFormatException e) { throw new ConfigException("Invalid DB port number: " + sDbPort); } LOG.info("Starting up Derby network server on TCP port " + dbPort); } else { LOG.info("No Derby Port specified, not starting up Derby Network Server"); } try { logDatabase = new LogDatabase(configFile.getParentFile(), dbPort); requestLogger = new DatabaseRequestLogger(logDatabase); requestLoggerThread = new Thread(requestLogger); requestLoggerThread.start(); } catch (Exception e) { throw new ConfigException("Could not initialize internal Derby Database", e); } application.start(rootPreferences); }
From source file:org.wso2.carbon.registry.extensions.internal.RegistrySCMServiceComponent.java
private void registerConnections(RegistryService registryService) throws RegistryException { String configPath = CarbonUtils.getRegistryXMLPath(); if (configPath != null) { File registryXML = new File(configPath); if (registryXML.exists()) { try { CurrentSession.setCallerTenantId(MultitenantConstants.SUPER_TENANT_ID); FileInputStream fileInputStream = new FileInputStream(registryXML); StAXOMBuilder builder = new StAXOMBuilder( CarbonUtils.replaceSystemVariablesInXml(fileInputStream)); OMElement configElement = builder.getDocumentElement(); SecretResolver secretResolver = SecretResolverFactory.create(configElement, false); OMElement scm = configElement.getFirstChildWithName(new QName("scm")); if (scm != null) { ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10); Iterator connections = scm.getChildrenWithName(new QName("connection")); while (connections.hasNext()) { OMElement connection = (OMElement) connections.next(); String checkOutURL = connection.getAttributeValue(new QName("checkOutURL")); // Read-Only by default, and can be disabled if needed by setting // Read-Only to false. boolean readOnly = !Boolean.toString(false) .equalsIgnoreCase(connection.getAttributeValue(new QName("readOnly"))); String checkInURL = connection.getAttributeValue(new QName("checkInURL")); String workingDir = connection.getAttributeValue(new QName("workingDir")); String mountPoint = connection.getAttributeValue(new QName("mountPoint")); String username = connection.getFirstChildWithName(new QName("username")).getText(); String password = connection.getFirstChildWithName(new QName("password")).getText(); int updateFrequency = DEFAULT_UPDATE_FREQUENCY; try { updateFrequency = Integer .parseInt(connection.getAttributeValue(new QName("updateFrequency"))); } catch (NumberFormatException ignore) { }//from w w w.jav a2 s . com UserRegistry registry = registryService .getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME); File directory = new File(workingDir); if (!directory.exists() && !directory.isDirectory()) { log.error("A valid directory was not found in path: " + workingDir); continue; } String filePath = directory.getAbsolutePath(); if (!registry.resourceExists(mountPoint)) { Collection collection = registry.newCollection(); collection.setProperty(RegistryConstants.REGISTRY_NON_RECURSIVE, "true"); registry.put(mountPoint, collection); } loadRegistryResources(registry, directory, filePath, mountPoint); ExternalContentHandler externalContentHandler = new ExternalContentHandler(); externalContentHandler.setFilePath(filePath); externalContentHandler.setMountPath(mountPoint); URLMatcher urlMatcher = new URLMatcher(); urlMatcher .setPattern(Pattern.quote(mountPoint) + "($|" + RegistryConstants.PATH_SEPARATOR + ".*|" + RegistryConstants.URL_SEPARATOR + ".*)"); RegistryContext registryContext = registry.getRegistryContext(); registryContext.registerNoCachePath(mountPoint); registryContext.getHandlerManager().addHandler(null, urlMatcher, externalContentHandler, HandlerLifecycleManager.TENANT_SPECIFIC_SYSTEM_HANDLER_PHASE); executorService .scheduleWithFixedDelay( new SCMUpdateTask(directory, checkOutURL, checkInURL, readOnly, externalContentHandler, username, CommonUtil .getResolvedPassword(secretResolver, "scm", password)), 0, updateFrequency, TimeUnit.MINUTES); } } } catch (XMLStreamException e) { log.error("Unable to parse registry.xml", e); } catch (IOException e) { log.error("Unable to read registry.xml", e); } catch (CarbonException e) { log.error("An error occurred during system variable replacement", e); } finally { CurrentSession.removeCallerTenantId(); } } } }
From source file:org.apache.axis2.clustering.tribes.MembershipManager.java
public void setupStaticMembershipManagement(StaticMembershipInterceptor staticMembershipInterceptor) { this.staticMembershipInterceptor = staticMembershipInterceptor; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleWithFixedDelay(new MemberListSenderTask(), 5, 5, TimeUnit.SECONDS); }
From source file:com.meltmedia.dropwizard.etcd.cluster.ClusterAssignmentIT.java
@Before public void setUp() throws Exception { executor = Executors.newScheduledThreadPool(10); nodeDir = factoryRule.getFactory().newDirectory("/app/nodes", new TypeReference<ClusterNode>() { });/*from w ww .j av a 2 s . c o m*/ processDir = factoryRule.getFactory().newDirectory("/app/streams"); MappedEtcdDirectory<ClusterProcess> processNodeDir = processDir.newDirectory("/processes", new TypeReference<ClusterProcess>() { }); MappedEtcdDirectory<ProcessorNode> processorNodeDir = processDir.newDirectory("/processors", new TypeReference<ProcessorNode>() { }); node1 = new ClusterNode().withId("node1").withStartedAt(new DateTime()); MetricRegistry registry1 = new MetricRegistry(); registry1.addListener(listener1 = mock(MetricRegistryListener.class)); clusterService1 = ClusterService.builder().withEtcdFactory(factoryRule.getFactory()).withExecutor(executor) .withNodesDirectory(nodeDir).withThisNode(node1).withMetricRegistry(registry1).build(); processService1 = clusterService1.newProcessService(processDir, ClusterAssignmentIT::toLifecycle, new TypeReference<ObjectNode>() { }); node2 = new ClusterNode().withId("node2").withStartedAt(new DateTime()); clusterService2 = ClusterService.builder().withEtcdFactory(factoryRule.getFactory()).withExecutor(executor) .withNodesDirectory(nodeDir).withThisNode(node2).withMetricRegistry(new MetricRegistry()).build(); processService2 = clusterService2.newProcessService(processDir, ClusterAssignmentIT::toLifecycle, new TypeReference<ObjectNode>() { }); node3 = new ClusterNode().withId("node3").withStartedAt(new DateTime()); clusterService3 = ClusterService.builder().withEtcdFactory(factoryRule.getFactory()).withExecutor(executor) .withNodesDirectory(nodeDir).withThisNode(node3).withMetricRegistry(new MetricRegistry()).build(); processService3 = clusterService3.newProcessService(processDir, ClusterAssignmentIT::toLifecycle, new TypeReference<ObjectNode>() { }); dao = processNodeDir.newDao(); processorDao = processorNodeDir.newDao(); latchFactory = new AssignmentLatchFactory(factoryRule.getFactory().getWatchService(), processNodeDir.getPath()); }