Example usage for java.util.concurrent Executors newScheduledThreadPool

List of usage examples for java.util.concurrent Executors newScheduledThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newScheduledThreadPool.

Prototype

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

Source Link

Document

Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:com.vadimfrolov.duorem.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create action bar as a toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
    setSupportActionBar(toolbar);/*from   ww  w.  ja  va  2s.  c  o m*/

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.registerOnSharedPreferenceChangeListener(this);

    mViewName = (TextView) findViewById(R.id.id);
    // mViewAddress = (TextView) findViewById(R.id.content);
    mIconAlive = (ImageView) findViewById(R.id.alive);
    mBtnTogglePower = (Button) findViewById(R.id.btn_toggle_power);
    mBtnRestart = (Button) findViewById(R.id.btn_restart);
    mViewStatus = (TextView) findViewById(R.id.text_status);

    mViewStatus.setMovementMethod(new ScrollingMovementMethod());

    Gson gson = new Gson();
    String targetJson = mPrefs.getString(KEY_PREF_TARGET, "");
    if (targetJson.length() > 0) {
        mTarget = gson.fromJson(targetJson, HostBean.class);
    }

    mSshTasks = new Stack<>();
    mDelegate = this;
    mIsConnected = false;

    mBtnRestart.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stopTargetPolling();

            RemoteCommand cmd = new RemoteCommand(mTarget, RemoteCommand.SSH);
            cmd.command = "sudo shutdown -r now";
            mSshTasks.push(new RemoteAsyncTask(mDelegate));
            mSshTasks.peek().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, cmd);

            logForUser(getResources().getString(R.string.reboot_sent));
        }
    });
    mBtnTogglePower.setOnClickListener(mPowerActor);

    // create a pool with only 3 threads
    mSch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(3);
    mSch.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
}

From source file:com.netflix.dyno.queues.redis.RedisDynoQueue.java

public RedisDynoQueue(String redisKeyPrefix, String queueName, Set<String> allShards, String shardName,
        ExecutorService dynoCallExecutor) {
    this.redisKeyPrefix = redisKeyPrefix;
    this.queueName = queueName;
    this.allShards = allShards.stream().collect(Collectors.toList());
    this.shardName = shardName;
    this.messageStoreKey = redisKeyPrefix + ".MESSAGE." + queueName;
    this.myQueueShard = getQueueShardKey(queueName, shardName);

    ObjectMapper om = new ObjectMapper();
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    om.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    om.setSerializationInclusion(Include.NON_NULL);
    om.setSerializationInclusion(Include.NON_EMPTY);
    om.disable(SerializationFeature.INDENT_OUTPUT);

    this.om = om;
    this.monitor = new QueueMonitor(queueName, shardName);
    this.prefetchedIds = new LinkedBlockingQueue<>();
    this.executorService = dynoCallExecutor;

    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> processUnacks(), unackScheduleInMS,
            unackScheduleInMS, TimeUnit.MILLISECONDS);
    Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> prefetchIds(), 0, 10, TimeUnit.MILLISECONDS);

    logger.info(RedisDynoQueue.class.getName() + " is ready to serve " + queueName);

}

From source file:com.turn.griffin.control.GriffinControlManager.java

public GriffinControlManager(GriffinModule griffinModule) {

    Preconditions.checkNotNull(griffinModule);
    this.griffinModule = griffinModule;

    Preconditions.checkState(!StringUtils.isBlank(GriffinModule.ZOOKEEPER), "Zookeeper is not defined");
    Preconditions.checkState(!StringUtils.isBlank(GriffinModule.BROKERS), "Brokers are not defined");
    String zookeeper = GriffinModule.ZOOKEEPER;
    String brokers = GriffinModule.BROKERS;

    /* Start the consumer before the producer to trigger topic creation */
    /* Start control channel consumer */
    this.incomingCntrlMsgQueue = new ArrayBlockingQueue<>(CONTROL_TOPIC_CONSUMER_QUEUE_SIZE);

    /* The groupId should be unique to avoid conflict with other consumers running on this machine */
    String consumerGroupId = GriffinKafkaTopicNameUtil
            .getControlTopicConsumerGroupId(new String[] { getMyServerId(), this.getClass().getSimpleName() });
    this.controlConsumer = new GriffinConsumer(zookeeper, consumerGroupId,
            GriffinKafkaTopicNameUtil.getControlTopicNameForConsumer(), CONTROL_TOPIC_CONSUMER_THREADS,
            new Properties(), incomingCntrlMsgQueue);

    /* Start a producer for control messages */
    this.controlProducer = new GriffinProducer(brokers);

    /* Thread pool to process all control commands and messages */
    this.controlThreadPool = Executors.newScheduledThreadPool(CONTROL_THREAD_POOL_COUNT);

    /* Start resource discovery */
    scheduleControlJob(// w ww  .  ja va2s . c  om
            new GriffinResourceDiscoveryTask(this, GriffinResourceDiscoveryTask.Action.SEND_GLOBAL_FILE_INFO),
            new Random().nextInt(GriffinModule.RESOURCE_DISCOVERY_INTERVAL_MS), TimeUnit.MILLISECONDS);

    /* A thread to create suitable runnable for incoming control messages */
    scheduleControlJob(this, 0, TimeUnit.SECONDS);
}

From source file:org.sample.jms.SampleQueueSender.java

public void calculate() {

    Runnable messagePerSecond = new Runnable() {
        public void run() {
            log.error("Messages per second " + messageCount);
            messageCount = 0;//from   w w w  .j av  a 2  s .  c o m
        }
    };

    ScheduledExecutorService executor = Executors.newScheduledThreadPool(0);
    executor.scheduleAtFixedRate(messagePerSecond, 1, 1, TimeUnit.SECONDS);
}

From source file:io.gromit.uaparser.Parser.java

/**
 * Start schedule./*from  www .ja va  2s .  c  om*/
 *
 * @return the parser
 */
public Parser startSchedule() {
    scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            initialize(uaRegexYaml);
        }
    }, 0, 1, TimeUnit.HOURS);
    return this;
}

From source file:io.smartspaces.example.activity.externalproxy.webappproxy.SmartSpacesExternalProxyServlet.java

@Override
public void init() throws ServletException {
    threadPool = Executors.newScheduledThreadPool(100);
    log = new Jdk14Logger("goober");

    log.info("Starting proxy server");
    try {//from  w  w w  . j  av  a  2  s.c o  m
        super.init();

        final String contents = getFunctionContent("deviceorientation");

        mobileServer = new NettyWebServer("mobile-server", WEBSERVER_PORT_MOBILE, threadPool, log);
        mobileServer.addDynamicContentHandler(URL_PREFIX_MOBILE_CONTENT, true, new HttpDynamicRequestHandler() {
            @Override
            public void handle(HttpRequest request, HttpResponse response) {

                response.setContentType("text/html");
                try {
                    Files.copyStream(new ByteArrayInputStream(contents.getBytes()), response.getOutputStream(),
                            false);
                } catch (IOException e) {
                    log.error("Could not write response", e);
                }
            }
        });

        mobileWebSocketHandlerFactory = new MultipleConnectionWebServerWebSocketHandlerFactory(
                new MultipleConnectionWebSocketHandler() {

                    @Override
                    public void handleNewWebSocketConnection(String connectionId) {
                        log.info(
                                String.format("Got web socket connection from mobile device %s", connectionId));
                    }

                    @Override
                    public void handleWebSocketClose(String connectionId) {
                        log.info(String.format("Lost web socket connection from mobile device %s",
                                connectionId));
                    }

                    @Override
                    public void handleWebSocketReceive(String connectionId, Object d) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> data = (Map<String, Object>) d;
                        data.put("id", connectionId);

                        smartSpacesWebSocketHandlerFactory.sendJson(data);
                    }
                }, log);

        mobileServer.setWebSocketHandlerFactory(URL_PREFIX_WEBSOCKET_MOBILE, mobileWebSocketHandlerFactory);
        mobileServer.startup();

        smartSpacesServer = new NettyWebServer("smartspaces-server", WEBSERVER_PORT_SMARTSPACES, threadPool,
                log);

        smartSpacesWebSocketHandlerFactory = new MultipleConnectionWebServerWebSocketHandlerFactory(
                new MultipleConnectionWebSocketHandler() {

                    @Override
                    public void handleNewWebSocketConnection(String connectionId) {
                        log.info(String.format("Got web socket connection from Smart Spaces %s", connectionId));
                    }

                    @Override
                    public void handleWebSocketClose(String connectionId) {
                        log.info(
                                String.format("Lost web socket connection from Smart Spaces %s", connectionId));
                    }

                    @Override
                    public void handleWebSocketReceive(String connectionId, Object d) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> data = (Map<String, Object>) d;
                    }
                }, log);
        smartSpacesServer.setWebSocketHandlerFactory(URL_PREFIX_WEBSOCKET_SMARTSPACES,
                smartSpacesWebSocketHandlerFactory);

        smartSpacesServer.startup();

        log.info("Servers started");
    } catch (Exception e) {
        log.error("Could not start up proxy", e);
    }
}

From source file:swift.application.filesystem.cs.SwiftFuseClient.java

SwiftFuseClient(long expFile) {
    this.attributes = Collections.synchronizedMap(new HashMap<String, GetAttrOperation.Result>());
    this.expirationDateAttr = Collections.synchronizedMap(new HashMap<String, Long>());
    this.defaultExpirationAttr = expFile;
    this.dirs = Collections.synchronizedMap(new HashMap<String, GetDirOperation.Result>());
    this.expirationDateDir = Collections.synchronizedMap(new HashMap<String, Long>());
    this.defaultExpirationDir = expFile;

    this.threads = Executors.newFixedThreadPool(2);
    Executors.newScheduledThreadPool(2).scheduleWithFixedDelay(this.removeExpired(),
            this.defaultExpirationAttr / 2, this.defaultExpirationAttr, TimeUnit.MILLISECONDS);
}

From source file:org.construct_infrastructure.io.MessageReader.java

/**
 * Creates a new message reader that will operate over the given InputStream.
 * /*from  www  .j a v  a  2 s  . c  o  m*/
 * @param an_inputStream
 *           the InputStream on which to read messages.
 */
public MessageReader(final InputStream an_inputStream, ExecutorService an_executorService) {
    my_errorOccured = false;
    my_logger = Logger.getLogger(getClass().getName());
    my_logger.setLevel(Level.WARNING);
    my_inputStream = new BufferedInputStream(an_inputStream);
    my_messageList = new LinkedList();
    my_keepReading = true;
    an_executorService.execute(this);
    my_service_scheduler = Executors.newScheduledThreadPool(1);
    my_service_scheduler.scheduleWithFixedDelay(my_listenerMonitor, 0, FIVE_HUNDRED, TimeUnit.MILLISECONDS);
    my_timeout = TWO_MINS_IN_MS;
    my_stopwatch = new StopWatch();
    my_stopwatch.start();
}

From source file:interactivespaces.example.activity.externalproxy.webappproxy.InteractiveSpacesExternalProxyServlet.java

@Override
public void init() throws ServletException {
    threadPool = Executors.newScheduledThreadPool(100);
    log = new Jdk14Logger("goober");

    log.info("Starting proxy server");
    try {//  w ww. java2 s.  c om
        super.init();

        final String contents = getFunctionContent("deviceorientation");

        mobileServer = new NettyWebServer("mobile-server", WEBSERVER_PORT_MOBILE, threadPool, log);
        mobileServer.addDynamicContentHandler(URL_PREFIX_MOBILE_CONTENT, true, new HttpDynamicRequestHandler() {
            @Override
            public void handle(HttpRequest request, HttpResponse response) {

                response.setContentType("text/html");
                try {
                    Files.copyStream(new ByteArrayInputStream(contents.getBytes()), response.getOutputStream(),
                            false);
                } catch (IOException e) {
                    log.error("Could not write response", e);
                }
            }
        });

        mobileWebSocketHandlerFactory = new MultipleConnectionWebServerWebSocketHandlerFactory(
                new MultipleConnectionWebSocketHandler() {

                    @Override
                    public void handleNewWebSocketConnection(String connectionId) {
                        log.info(
                                String.format("Got web socket connection from mobile device %s", connectionId));
                    }

                    @Override
                    public void handleWebSocketClose(String connectionId) {
                        log.info(String.format("Lost web socket connection from mobile device %s",
                                connectionId));
                    }

                    @Override
                    public void handleWebSocketReceive(String connectionId, Object d) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> data = (Map<String, Object>) d;
                        data.put("id", connectionId);

                        interactiveSpacesWebSocketHandlerFactory.sendJson(data);
                    }
                }, log);

        mobileServer.setWebSocketHandlerFactory(URL_PREFIX_WEBSOCKET_MOBILE, mobileWebSocketHandlerFactory);
        mobileServer.startup();

        interactiveSpacesServer = new NettyWebServer("interactivespaces-server",
                WEBSERVER_PORT_INTERACTIVESPACES, threadPool, log);

        interactiveSpacesWebSocketHandlerFactory = new MultipleConnectionWebServerWebSocketHandlerFactory(
                new MultipleConnectionWebSocketHandler() {

                    @Override
                    public void handleNewWebSocketConnection(String connectionId) {
                        log.info(String.format("Got web socket connection from Interactive Spaces %s",
                                connectionId));
                    }

                    @Override
                    public void handleWebSocketClose(String connectionId) {
                        log.info(String.format("Lost web socket connection from Interactive Spaces %s",
                                connectionId));
                    }

                    @Override
                    public void handleWebSocketReceive(String connectionId, Object d) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> data = (Map<String, Object>) d;
                    }
                }, log);
        interactiveSpacesServer.setWebSocketHandlerFactory(URL_PREFIX_WEBSOCKET_INTERACTIVESPACES,
                interactiveSpacesWebSocketHandlerFactory);

        interactiveSpacesServer.startup();

        log.info("Servers started");
    } catch (Exception e) {
        log.error("Could not start up proxy", e);
    }
}

From source file:org.wso2.andes.kernel.AndesKernelBoot.java

/**
 * This will boot up all the components in Andes kernel and bring the server to working state
 *//*from ww  w .  j  a v  a 2 s.c o m*/
public static void initializeComponents() throws AndesException {
    isKernelShuttingDown = false;
    //loadConfigurations - done from outside
    //startAndesStores - done from outside
    int threadPoolCount = 1;
    andesRecoveryTaskScheduler = Executors.newScheduledThreadPool(threadPoolCount);
    expiryMessageDeletionTaskScheduler = Executors.newScheduledThreadPool(threadPoolCount);
    startHouseKeepingThreads();
    createDefinedProtocolArtifacts();
    syncNodeWithClusterState();
    registerMBeans();
    startThriftServer();
    Andes.getInstance().startSafeZoneUpdateWorkers();
    int slotDeletingWorkerCount = AndesConfigurationManager
            .readValue(AndesConfiguration.PERFORMANCE_TUNING_SLOT_DELETE_WORKER_COUNT);
    int maxNumberOfPendingSlotsToDelete = AndesConfigurationManager
            .readValue(AndesConfiguration.PERFORMANCE_TUNING_SLOT_DELETE_QUEUE_DEPTH_WARNING_THRESHOLD);
    SlotDeletionExecutor.getInstance().init(slotDeletingWorkerCount, maxNumberOfPendingSlotsToDelete);
}