List of usage examples for java.util.concurrent ScheduledThreadPoolExecutor ScheduledThreadPoolExecutor
public ScheduledThreadPoolExecutor(int corePoolSize)
From source file:com.inmobi.messaging.publisher.AuditService.java
void init(ClientConfig config) throws IOException { if (isInit) { return;/* w ww . j a v a 2 s .c o m*/ } windowSize = config.getInteger(WINDOW_SIZE_KEY, DEFAULT_WINDOW_SIZE); aggregateWindowSize = config.getInteger(AGGREGATE_WINDOW_KEY, DEFAULT_AGGREGATE_WINDOW_SIZE); executor = new ScheduledThreadPoolExecutor(1); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOG.error("Unable to find the hostanme of the local box,audit packets" + " won't contain hostname"); hostname = ""; } worker = new AuditWorker(); executor.scheduleWithFixedDelay(worker, aggregateWindowSize, aggregateWindowSize, TimeUnit.SECONDS); // setting init flag to true isInit = true; }
From source file:org.apache.hadoop.hbase.util.TestHBaseFsckOneRS.java
@BeforeClass public static void setUpBeforeClass() throws Exception { TEST_UTIL.getConfiguration().set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, MasterSyncObserver.class.getName()); conf.setInt("hbase.regionserver.handler.count", 2); conf.setInt("hbase.regionserver.metahandler.count", 30); conf.setInt("hbase.htable.threads.max", POOL_SIZE); conf.setInt("hbase.hconnection.threads.max", 2 * POOL_SIZE); conf.setInt("hbase.hbck.close.timeout", 2 * REGION_ONLINE_TIMEOUT); conf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 8 * REGION_ONLINE_TIMEOUT); TEST_UTIL.startMiniCluster(1);/*from www . j a va 2 s .co m*/ tableExecutorService = new ThreadPoolExecutor(1, POOL_SIZE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("testhbck")); hbfsckExecutorService = new ScheduledThreadPoolExecutor(POOL_SIZE); AssignmentManager assignmentManager = TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager(); regionStates = assignmentManager.getRegionStates(); connection = (ClusterConnection) TEST_UTIL.getConnection(); admin = connection.getAdmin(); admin.setBalancerRunning(false, true); TEST_UTIL.waitUntilAllRegionsAssigned(TableName.META_TABLE_NAME); TEST_UTIL.waitUntilAllRegionsAssigned(TableName.NAMESPACE_TABLE_NAME); }
From source file:dk.netarkivet.common.lifecycle.PeriodicTaskExecutor.java
/** * Builds an executor for a set of tasks. * @param tasks the task definitions./* w w w . j av a 2 s . com*/ */ public PeriodicTaskExecutor(PeriodicTask... tasks) { ArgumentNotValid.checkNotNull(tasks, "tasks"); ArgumentNotValid.checkNotNullOrEmpty(Arrays.asList(tasks), "tasks"); this.tasks = tasks; this.exec = new ScheduledThreadPoolExecutor(tasks.length); alive = true; String id = ""; for (PeriodicTask t : tasks) { ScheduledFuture<?> future = exec.scheduleAtFixedRate(t.task, t.secondsBeforeFirstExec, t.secondsBetweenExec, TimeUnit.SECONDS); t.setFuture(future); id += "_" + t.taskId; } checkerThread = new Thread(id.hashCode() + "-checker") { public void run() { while (alive) { checkExecution(); try { Thread.sleep(TimeUtils.SECOND_IN_MILLIS); } catch (InterruptedException e) { if (log.isTraceEnabled()) { log.trace("checkerThread interrupted."); } } } } }; checkerThread.start(); }
From source file:edu.berkeley.sparrow.examples.SimpleFrontend.java
public void run(String[] args) { try {/*from w w w. j a v a 2 s.co m*/ OptionParser parser = new OptionParser(); parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class); parser.accepts("help", "print help statement"); OptionSet options = parser.parse(args); if (options.has("help")) { parser.printHelpOn(System.out); System.exit(-1); } // Logger configuration: log to the console BasicConfigurator.configure(); LOG.setLevel(Level.DEBUG); Configuration conf = new PropertiesConfiguration(); if (options.has("c")) { String configFile = (String) options.valueOf("c"); conf = new PropertiesConfiguration(configFile); } int arrivalPeriodMillis = conf.getInt(JOB_ARRIVAL_PERIOD_MILLIS, DEFAULT_JOB_ARRIVAL_PERIOD_MILLIS); int experimentDurationS = conf.getInt(EXPERIMENT_S, DEFAULT_EXPERIMENT_S); LOG.debug("Using arrival period of " + arrivalPeriodMillis + " milliseconds and running experiment for " + experimentDurationS + " seconds."); int tasksPerJob = conf.getInt(TASKS_PER_JOB, DEFAULT_TASKS_PER_JOB); int taskDurationMillis = conf.getInt(TASK_DURATION_MILLIS, DEFAULT_TASK_DURATION_MILLIS); int schedulerPort = conf.getInt(SCHEDULER_PORT, SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT); String schedulerHost = conf.getString(SCHEDULER_HOST, DEFAULT_SCHEDULER_HOST); client = new SparrowFrontendClient(); client.initialize(new InetSocketAddress(schedulerHost, schedulerPort), APPLICATION_ID, this); JobLaunchRunnable runnable = new JobLaunchRunnable(tasksPerJob, taskDurationMillis); ScheduledThreadPoolExecutor taskLauncher = new ScheduledThreadPoolExecutor(1); taskLauncher.scheduleAtFixedRate(runnable, 0, arrivalPeriodMillis, TimeUnit.MILLISECONDS); long startTime = System.currentTimeMillis(); LOG.debug("sleeping"); while (System.currentTimeMillis() < startTime + experimentDurationS * 1000) { Thread.sleep(100); } taskLauncher.shutdown(); } catch (Exception e) { LOG.error("Fatal exception", e); } }
From source file:org.apache.qpid.server.virtualhost.VirtualHostImpl.java
public VirtualHostImpl(VirtualHostRegistry virtualHostRegistry, StatisticsGatherer brokerStatisticsGatherer, SecurityManager parentSecurityManager, VirtualHostConfiguration hostConfig) throws Exception { if (hostConfig == null) { throw new IllegalArgumentException("HostConfig cannot be null"); }/*w ww. j a va2 s.co m*/ if (hostConfig.getName() == null || hostConfig.getName().length() == 0) { throw new IllegalArgumentException("Illegal name (" + hostConfig.getName() + ") for virtualhost."); } _virtualHostRegistry = virtualHostRegistry; _brokerStatisticsGatherer = brokerStatisticsGatherer; _vhostConfig = hostConfig; _name = _vhostConfig.getName(); _dtxRegistry = new DtxRegistry(); _id = UUIDGenerator.generateVhostUUID(_name); CurrentActor.get().message(VirtualHostMessages.CREATED(_name)); _securityManager = new SecurityManager(parentSecurityManager, _vhostConfig.getConfig().getString("security.acl")); _connectionRegistry = new ConnectionRegistry(); _connectionRegistry.addRegistryChangeListener(this); _houseKeepingTasks = new ScheduledThreadPoolExecutor(_vhostConfig.getHouseKeepingThreadCount()); _queueRegistry = new DefaultQueueRegistry(this); _exchangeFactory = new DefaultExchangeFactory(this); _exchangeRegistry = new DefaultExchangeRegistry(this); _bindingFactory = new BindingFactory(this); _messageStore = configureMessageStore(hostConfig); activateNonHAMessageStore(); initialiseStatistics(); _messageStore.addEventListener(this, Event.PERSISTENT_MESSAGE_SIZE_OVERFULL); _messageStore.addEventListener(this, Event.PERSISTENT_MESSAGE_SIZE_UNDERFULL); }
From source file:org.orbisgis.orbisserver.baseserver.model.Session.java
/** * Sets the properties of the Session./*from w w w . j av a 2 s . c om*/ * @param propertyMap Map containing the properties of the session. */ public void setProperties(Map<String, Object> propertyMap) { if (propertyMap.containsKey(PROPERTY_EXPIRATION_TIME_MILLIS)) { this.expirationTimeMillis = (long) propertyMap.get(PROPERTY_EXPIRATION_TIME_MILLIS); } else { this.expirationTimeMillis = -1; } if (propertyMap.containsKey(ServiceFactory.DATA_SOURCE_PROP)) { this.ds = (DataSource) propertyMap.get(ServiceFactory.DATA_SOURCE_PROP); } if (propertyMap.containsKey(ServiceFactory.EXECUTOR_SERVICE_PROP)) { this.executorService = (ExecutorService) propertyMap.get(ServiceFactory.EXECUTOR_SERVICE_PROP); } if (propertyMap.containsKey(ServiceFactory.WORKSPACE_FOLDER_PROP)) { this.workspaceFolder = (File) propertyMap.get(ServiceFactory.WORKSPACE_FOLDER_PROP); } if (propertyMap.containsKey(JOB_POOL_SIZE)) { this.resultExpirationExecutor = new ScheduledThreadPoolExecutor((int) propertyMap.get(JOB_POOL_SIZE)); } else { this.resultExpirationExecutor = new ScheduledThreadPoolExecutor(BASE_POOL_SIZE); } if (propertyMap.containsKey(ServiceFactory.DATA_SOURCE_PROP)) { this.serviceList = (List<Service>) propertyMap.get(SERVICE_LIST); } else { this.serviceList = new ArrayList<>(); LOGGER.info("No services available on starting the session."); } }
From source file:com.sbhstimetable.sbhs_timetable_android.backend.service.NotificationService.java
/** * Handle action Baz in the provided background thread with the provided * parameters.// w ww .j a va 2 s. c o m */ private void handleNotificationUpdate() { NotificationManager m = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean("notifications_enable", false)) { // only show a notification if it's configured m.cancel(NOTIFICATION_NEXT); return; } NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); if (BelltimesJson.getInstance() == null) return; BelltimesJson.Bell next = BelltimesJson.getInstance().getNextBell(); if (next == null) { // Show tomorrow. TODO m.cancel(NOTIFICATION_NEXT); return; } String title = next.getLabel(); Integer[] b = next.getBell(); b[0] = b[0] % 12; if (b[0] == 0) b[0] = 12; String subText = "at " + String.format("%02d:%02d", b); subText += (next.getBell()[0] >= 12 ? "pm" : "am"); if (next.isPeriod() && TodayJson.getInstance() != null) { TodayJson.Period p = TodayJson.getInstance().getPeriod(next.getPeriodNumber()); title = p.name() + " in " + p.room(); subText += " with " + p.teacher(); } builder.setContentTitle(title); builder.setContentText(subText); if (DateTimeHelper.milliSecondsUntilNextEvent() < 0) { Log.e("notificationService", "an event in the past? bailing out..."); return; } Log.i("notificationService", "updating. time until next event: " + DateTimeHelper.formatToCountdown(DateTimeHelper.milliSecondsUntilNextEvent())); ScheduledExecutorService ses = new ScheduledThreadPoolExecutor(1); m.notify(NOTIFICATION_NEXT, builder.build()); ses.schedule(new NotificationRunner(this), DateTimeHelper.milliSecondsUntilNextEvent(), TimeUnit.MILLISECONDS); }
From source file:org.montanafoodhub.app.HubApplication.java
public void stopHubThreads() { _startHubThreads = false;// ww w . ja v a2s . c o m if (_hubInitialized == true) { Log.w(LogTag, "stopHubThreads exec.getQueue().size() = " + exec.getQueue().size()); if (exec.getQueue().size() != 0) { buyerHubScheduledFuture.cancel(false); itemHubScheduledFuture.cancel(false); orderHubScheduledFuture.cancel(false); producerHubScheduledFuture.cancel(false); certificationHubScheduledFuture.cancel(false); adHubScheduledFuture.cancel(false); } exec.shutdownNow(); exec = null; exec = new ScheduledThreadPoolExecutor(4); Log.w(LogTag, "stopHubThreads exec.getQueue().size() = " + exec.getQueue().size()); } }
From source file:net.roboconf.iaas.openstack.IaasOpenstack.java
@Override public String createVM(String machineImageId, String ipMessagingServer, String channelName, String applicationName) throws IaasException, CommunicationToIaasException { if (machineImageId == null || "".equals(machineImageId)) machineImageId = this.machineImageId; // Normally we use flavor names in the configuration, not IDs // But lets's assume it can be an ID... String flavorId = this.flavor; Flavors flavors = this.novaClient.flavors().list(true).execute(); for (Flavor f : flavors) { if (f.getName().equals(this.flavor)) flavorId = f.getId();/*from w w w . j a va2 s . co m*/ } ServerForCreate serverForCreate = new ServerForCreate(); serverForCreate.setName(applicationName + "." + channelName); serverForCreate.setFlavorRef(flavorId); serverForCreate.setImageRef(machineImageId); if (this.keypair != null) serverForCreate.setKeyName(this.keypair); serverForCreate.getSecurityGroups().add(new ServerForCreate.SecurityGroup(this.securityGroup)); // User data will be retrieved (like on Amazon WS) on guest OS as // http://169.254.169.254/latest/user-data String userData = "applicationName=" + applicationName + "\nmachineName=" + channelName //TBD machineName=channelName + "\nchannelName=" + channelName + "\nipMessagingServer=" + ipMessagingServer; serverForCreate.setUserData(new String(Base64.encodeBase64(userData.getBytes()))); final Server server = this.novaClient.servers().boot(serverForCreate).execute(); System.out.println(server); // Wait for server to be in ACTIVE state, before associating floating IP try { final ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1); timer.scheduleAtFixedRate(new Runnable() { @Override public void run() { Server checked = IaasOpenstack.this.novaClient.servers().show(server.getId()).execute(); if ("ACTIVE".equals(checked.getStatus())) { timer.shutdown(); } } }, 10, 5, TimeUnit.SECONDS); timer.awaitTermination(120, TimeUnit.SECONDS); } catch (Exception ignore) { /*ignore*/ } // Associate floating IP if (this.floatingIpPool != null) { FloatingIps ips = this.novaClient.floatingIps().list().execute(); FloatingIp ip = null; for (FloatingIp ip2 : ips) { System.out.println("ip=" + ip2); ip = ip2; } //FloatingIp ip = ips.allocate(this.floatingIpPool).execute(); if (ip != null) { this.novaClient.servers().associateFloatingIp(server.getId(), ip.getIp()).execute(); } } return server.getId(); }
From source file:com.px100systems.data.plugin.persistence.DiskPersistence.java
/** * Resumes the stopped server/*from w ww .j ava 2 s . com*/ */ public void resume() { if (scheduler != null) scheduler.shutdown(); scheduler = new ScheduledThreadPoolExecutor(1); // One thread should be fine. Write-behind nature is single-threaded persist(); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { persist(); } }, writeBehindSeconds, writeBehindSeconds, TimeUnit.SECONDS); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { cleanup(); } }, cleanupHours, cleanupHours, TimeUnit.HOURS); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { compact(); } }, compactHours, compactHours, TimeUnit.HOURS); log.info("Started in-memory data storage persistence"); }