Java Code Examples for java.util.concurrent.Executors.newSingleThreadScheduledExecutor()

The following are Jave code examples for showing how to use newSingleThreadScheduledExecutor() of the java.util.concurrent.Executors class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: reading-and-annotate-rocketmq-3.4.6   File: SystemClock.java   View Source Code Vote up 7 votes
private void scheduleClockUpdating() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            now.set(System.currentTimeMillis());
        }
    }, precision, precision, TimeUnit.MILLISECONDS);
}
 
Example 2
Project: openNaEF   File: Notifier.java   View Source Code Vote up 6 votes
@Override
    public void contextInitialized(ServletContextEvent sce) {
        Notifier.start();

        // scheduled-notifier start
//        new WsScheduledNotifier();

        // webhook start
        Webhooks.instance();

        try {
            long pingDelay = NotifierConfig.instance().pingDelay();
            if (pingDelay > 0) {
                ScheduledExecutorService pinging = Executors.newSingleThreadScheduledExecutor();
                pinging.scheduleWithFixedDelay(
                        CommitNotifier::sendPing,
                        10L,
                        pingDelay,
                        TimeUnit.SECONDS);
            }
        } catch (IOException e) {
            Logs.common.error("ping", e);
        }

    }
 
Example 3
Project: java-coap   File: CoapServerBuilder.java   View Source Code Vote up 6 votes
@Override
protected CoapUdpMessaging buildCoapMessaging() {
    boolean isSelfCreatedExecutor = false;
    if (scheduledExecutorService == null) {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        isSelfCreatedExecutor = true;
    }

    if (blockSize != null && blockSize.isBert()) {
        throw new IllegalArgumentException("BlockSize with BERT support is defined only for CoAP overt TCP/TLS 2017 standard draft");
    }

    CoapUdpMessaging server = new CoapUdpMessaging(checkAndGetCoapTransport());

    server.setSpecialCoapTransactionPriority(blockTransferPriority);
    server.setTransmissionTimeout(transmissionTimeout);

    server.init(duplicationMaxSize, scheduledExecutorService, isSelfCreatedExecutor,
            midSupplier, maxQueueSize, defaultTransactionPriority, delayedTransactionTimeout, duplicatedCoapMessageCallback);

    return server;
}
 
Example 4
Project: WiFiProbeAnalysis   File: Monitor.java   View Source Code Vote up 6 votes
public void sendMsg() {
        System.out.println("sendMsg");
        ScheduledExecutorService newScheduledThreadPool = Executors.newSingleThreadScheduledExecutor();
        Random random = new Random();
//        int delay = random.nextInt(2) + 1;
        int delay = 3;
        System.out.println("delay = " + delay);

        newScheduledThreadPool.scheduleWithFixedDelay(new Monitor(), 1, delay, TimeUnit.SECONDS);
    }
 
Example 5
Project: Re-Collector   File: MemoryReporterService.java   View Source Code Vote up 6 votes
@Override
protected void doStart() {
    if (config.isEnable()) {
        this.scheduler = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder()
                        .setDaemon(true)
                        .setNameFormat("memory-reporter-thread")
                        .setUncaughtExceptionHandler((t, e) ->
                                log.error("Problem in memory reporter", e))
                        .build());

        this.scheduledJob = this.scheduler.scheduleAtFixedRate(() -> {
            reportGC();
            reportMemoryPool();
            reportMemoryUsage();
        }, config.getInterval(), config.getInterval(), TimeUnit.MILLISECONDS);
    }

    notifyStarted();
}
 
Example 6
Project: flume-release-1.7.0   File: GangliaServer.java   View Source Code Vote up 6 votes
/**
 * Start this server, causing it to poll JMX at the configured frequency.
 */
@Override
public void start() {
  try {
    socket = new DatagramSocket();
    hostname = InetAddress.getLocalHost().getHostName();
  } catch (SocketException ex) {
    logger.error("Could not create socket for metrics collection.");
    throw new FlumeException(
            "Could not create socket for metrics collection.", ex);
  } catch (Exception ex2) {
    logger.warn("Unknown error occured", ex2);
  }
  for (HostInfo host : hosts) {
    addresses.add(new InetSocketAddress(
            host.getHostName(), host.getPortNumber()));
  }
  collectorRunnable.server = this;
  if (service.isShutdown() || service.isTerminated()) {
    service = Executors.newSingleThreadScheduledExecutor();
  }
  service.scheduleWithFixedDelay(collectorRunnable, 0,
          pollFrequency, TimeUnit.SECONDS);
}
 
Example 7
Project: java-coap   File: DuplicationDetectorTest.java   View Source Code Vote up 6 votes
@Test
public void testDuplicationAfterCleanUpTimeout() throws Exception {
    final int timeout = 300;
    final int collectionSize = 1;
    DuplicationDetector detector = new DuplicationDetector(TimeUnit.MILLISECONDS, timeout, collectionSize, Executors.newSingleThreadScheduledExecutor());
    final int cleanupInterval = 100;
    detector.setCleanDelayMili(cleanupInterval);
    detector.start();
    try {
        CoapPacket packet = mock(CoapPacket.class);
        when(packet.getRemoteAddress()).thenReturn(InetSocketAddress.createUnresolved("testHost", 8080));
        when(packet.getMessageId()).thenReturn(9);

        CoapPacket firstIsDuplicated = detector.isMessageRepeated(packet);
        Thread.sleep(timeout + cleanupInterval + 10);
        CoapPacket secondIsDuplicated = detector.isMessageRepeated(packet);

        assertNull("insertion to empty duplicate check list fails", firstIsDuplicated);
        assertNull("second insertion after timeout with same id fails", secondIsDuplicated);
    } finally {
        detector.stop();
    }
}
 
Example 8
Project: flink-connectors   File: ReaderCheckpointHook.java   View Source Code Vote up 6 votes
@Override
public CompletableFuture<Checkpoint> triggerCheckpoint(
        long checkpointId, long checkpointTimestamp, Executor executor) throws Exception {

    final String checkpointName = createCheckpointName(checkpointId);

    // The method only offers an 'Executor', but we need a 'ScheduledExecutorService'
    // Because the hook currently offers no "shutdown()" method, there is no good place to
    // shut down a long lived ScheduledExecutorService, so we create one per request
    // (we should change that by adding a shutdown() method to these hooks)
    // ths shutdown 

    final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    final CompletableFuture<Checkpoint> checkpointResult =
            this.readerGroup.initiateCheckpoint(checkpointName, scheduledExecutorService);

    // Add a timeout to the future, to prevent long blocking calls
    scheduledExecutorService.schedule(() -> checkpointResult.cancel(false), triggerTimeout, TimeUnit.MILLISECONDS);

    // we make sure the executor is shut down after the future completes
    checkpointResult.handle((success, failure) -> scheduledExecutorService.shutdownNow());

    return checkpointResult;
}
 
Example 9
Project: talchain   File: NodeManager.java   View Source Code Vote up 5 votes
@Autowired
public NodeManager(SystemProperties config, EthereumListener ethereumListener,
                   ApplicationContext ctx, PeerConnectionTester peerConnectionManager) {
    this.config = config;
    this.ethereumListener = ethereumListener;
    this.peerConnectionManager = peerConnectionManager;

    PERSIST = config.peerDiscoveryPersist();
    if (PERSIST) peerSource = ctx.getBean(PeerSource.class);
    discoveryEnabled = config.peerDiscovery();

    key = config.getMyKey();
    homeNode = new Node(config.nodeId(), config.externalIp(), config.listenPort());
    table = new NodeTable(homeNode, config.isPublicHomeNode());

    logStatsTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            logger.trace("Statistics:\n {}", dumpAllStatistics());
        }
    }, 1 * 1000, 60 * 1000);

    this.pongTimer = Executors.newSingleThreadScheduledExecutor();
    for (Node node : config.peerActive()) {
        getNodeHandler(node).getNodeStatistics().setPredefined(true);
    }
}
 
Example 10
Project: GitHub   File: Countly.java   View Source Code Vote up 5 votes
/**
 * Constructs a Countly object.
 * Creates a new ConnectionQueue and initializes the session timer.
 */
Countly() {
    connectionQueue_ = new ConnectionQueue();
    Countly.userData = new UserData(connectionQueue_);
    timerService_ = Executors.newSingleThreadScheduledExecutor();
    timerService_.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            onTimer();
        }
    }, TIMER_DELAY_IN_SECONDS, TIMER_DELAY_IN_SECONDS, TimeUnit.SECONDS);
}
 
Example 11
Project: neoscada   File: Activator.java   View Source Code Vote up 5 votes
@Override
public void start ( final BundleContext context ) throws Exception
{
    logger.info ( "Starting bundle" );

    this.executor = Executors.newSingleThreadScheduledExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
    this.factory = new ConnectionAnalyzerFactory ( this.executor, context );
}
 
Example 12
Project: -Spring-SpringMVC-Mybatis-   File: SystemClock.java   View Source Code Vote up 5 votes
private void scheduleClockUpdating() {
	ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
		public Thread newThread(Runnable runnable) {
			Thread thread = new Thread(runnable, "System Clock");
			thread.setDaemon(true);
			return thread;
		}
	});
	scheduler.scheduleAtFixedRate(new Runnable() {
		public void run() {
			now.set(System.currentTimeMillis());
		}
	}, period, period, TimeUnit.MILLISECONDS);
}
 
Example 13
Project: iTAP-controller   File: SingletonTaskTest.java   View Source Code Vote up 5 votes
@Test
public void testReschedule() throws InterruptedException {
    ScheduledExecutorService ses =
        Executors.newSingleThreadScheduledExecutor();

    final Object tc = this;
    SingletonTask st1 = new SingletonTask(ses, new Runnable() {
        @Override
        public void run() {
            synchronized (tc) {
                ran += 1;
            }
            time = System.nanoTime();
        }
    });

    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);
    st1.reschedule(20, TimeUnit.MILLISECONDS);
    Thread.sleep(5);
    assertFalse("Check that task hasn't run yet", ran > 0);

    ses.shutdown();
    ses.awaitTermination(5, TimeUnit.SECONDS);

    assertEquals("Check that task ran only once", 1, ran);
}
 
Example 14
Project: neoscada   File: AutoReconnectController.java   View Source Code Vote up 5 votes
/**
 * Create a new reconnect controller for the provided connection
 * 
 * @param connection
 *            the connection to manage
 * @param reconnectDelay
 *            the minimum delay between reconnect attempts
 */
public AutoReconnectController ( final Connection connection, long reconnectDelay )
{
    this.connection = connection;
    this.reconnectDelay = reconnectDelay;

    if ( this.connection == null )
    {
        throw new IllegalArgumentException ( "'connection' must not be null" );
    }

    if ( reconnectDelay <= 0 )
    {
        reconnectDelay = DEFAULT_RECONNECT_DELAY;
    }

    final ThreadFactory threadFactory = new NamedThreadFactory ( "AutoReconnect/" + connection.getConnectionInformation ().toMaskedString () );
    synchronized ( this )
    {
        this.executor = Executors.newSingleThreadScheduledExecutor ( threadFactory );
    }

    this.connection.addConnectionStateListener ( this );

    if ( !Boolean.getBoolean ( "org.eclipse.scada.core.client.AutoReconnectController.disableZombieMode" ) )
    {
        this.zombieJob = this.executor.scheduleWithFixedDelay ( new Runnable () {

            @Override
            public void run ()
            {
                checkDead ();
            }
        }, reconnectDelay, reconnectDelay, TimeUnit.MILLISECONDS );
    }
}
 
Example 15
Project: lams   File: DriverManagerConnectionProviderImpl.java   View Source Code Vote up 4 votes
@Override
public void configure(Map configurationValues) {
	log.usingHibernateBuiltInConnectionPool();

	connectionCreator = buildCreator( configurationValues );

	final int minSize = ConfigurationHelper.getInt( MIN_SIZE, configurationValues, 1 );
	final int maxSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 );
	final int initialSize = ConfigurationHelper.getInt( INITIAL_SIZE, configurationValues, minSize );
	final long validationInterval = ConfigurationHelper.getLong( VALIDATION_INTERVAL, configurationValues, 30 );

	log.hibernateConnectionPoolSize( maxSize, minSize );

	log.debugf( "Initializing Connection pool with %s Connections", initialSize );
	for ( int i = 0; i < initialSize; i++ ) {
		connections.add( connectionCreator.createConnection() );
	}

	executorService = Executors.newSingleThreadScheduledExecutor();
	executorService.scheduleWithFixedDelay(
			new Runnable() {
				private boolean primed;
				@Override
				public void run() {
					int size = connections.size();

					if ( !primed && size >= minSize ) {
						// IMPL NOTE : the purpose of primed is to allow the pool to lazily reach its
						// defined min-size.
						log.debug( "Connection pool now considered primed; min-size will be maintained" );
						primed = true;
					}

					if ( size < minSize && primed ) {
						int numberToBeAdded = minSize - size;
						log.debugf( "Adding %s Connections to the pool", numberToBeAdded );
						for (int i = 0; i < numberToBeAdded; i++) {
							connections.add( connectionCreator.createConnection() );
						}
					}
					else if ( size > maxSize ) {
						int numberToBeRemoved = size - maxSize;
						log.debugf( "Removing %s Connections from the pool", numberToBeRemoved );
						for ( int i = 0; i < numberToBeRemoved; i++ ) {
							Connection connection = connections.poll();
							try {
								connection.close();
							}
							catch (SQLException e) {
								log.unableToCloseConnection( e );
							}
						}
					}
				}
			},
			validationInterval,
			validationInterval,
			TimeUnit.SECONDS
	);
}
 
Example 16
Project: elastic-apm-java-agent-poc   File: ApmAgent.java   View Source Code Vote up 4 votes
protected ScheduledExecutorService startQueue (final TimerTask task) {
  final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor ();
  executor.scheduleAtFixedRate (task, getInitialDelay (), getPeriod (), TimeUnit.MILLISECONDS);
  return executor;
}
 
Example 17
Project: JDA-Audio   File: AudioConnection.java   View Source Code Vote up 4 votes
private synchronized void setupCombinedExecutor()
{
    if (combinedAudioExecutor == null)
    {
        combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor( r ->
                new Thread(AudioManager.AUDIO_THREADS, r, threadIdentifier + " Combined Thread"));
        combinedAudioExecutor.scheduleAtFixedRate(() ->
        {
            try
            {
                List<String> users = new LinkedList<>();
                List<short[]> audioParts = new LinkedList<>();
                if (receiveHandler != null && receiveHandler.canReceiveCombined())
                {
                    long currentTime = System.currentTimeMillis();
                    for (Map.Entry<String, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet())
                    {
                        String user = entry.getKey();
                        Queue<Pair<Long, short[]>> queue = entry.getValue();

                        if (queue.isEmpty())
                            continue;

                        Pair<Long, short[]> audioData = queue.poll();
                        //Make sure the audio packet is younger than 100ms
                        while (audioData != null && currentTime - audioData.getLeft() > queueTimeout)
                        {
                            audioData = queue.poll();
                        }

                        //If none of the audio packets were younger than 100ms, then there is nothing to add.
                        if (audioData == null)
                        {
                            continue;
                        }
                        users.add(user);
                        audioParts.add(audioData.getRight());
                    }

                    if (!audioParts.isEmpty())
                    {
                        int audioLength = audioParts.get(0).length;
                        short[] mix = new short[1920];  //960 PCM samples for each channelId
                        int sample;
                        for (int i = 0; i < audioLength; i++)
                        {
                            sample = 0;
                            for (short[] audio : audioParts)
                            {
                                sample += audio[i];
                            }
                            if (sample > Short.MAX_VALUE)
                                mix[i] = Short.MAX_VALUE;
                            else if (sample < Short.MIN_VALUE)
                                mix[i] = Short.MIN_VALUE;
                            else
                                mix[i] = (short) sample;
                        }
                        receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix));
                    }
                    else
                    {
                        //No audio to mix, provide 20 MS of silence. (960 PCM samples for each channelId)
                        receiveHandler.handleCombinedAudio(new CombinedAudio(Collections.emptyList(), new short[1920]));
                    }
                }
            }
            catch (Exception e)
            {
                LOG.log(e);
            }
        }, 0, 20, TimeUnit.MILLISECONDS);
    }
}
 
Example 18
Project: TrackMeIfYouCanChat   File: ChatFrame.java   View Source Code Vote up 4 votes
public ChatFrame(String user,String di2p, String chat_id, Message msg) {
    initComponents();
    this.setTitle("ChatFrame - "+Client.nickname);
    jTextArea2.requestFocusInWindow();//Set focus on the TextArea the user is going to type
    jList1.setSelectionModel(new DisabledItemSelectionModel());//Set the custom selectionmodel, disable selection on user list
    chatid = chat_id;
    sender = new I2P_Send(di2p);
    sender.send(msg);
    jTextArea1.append("Waiting for "+ user +" to connect....." + "\n");
    exec2 = Executors.newSingleThreadScheduledExecutor();
    
    this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);//Dispose instead of exit app
    
    
    DefaultListModel jl1 = new DefaultListModel();//New model for the user that will be in the new chat
    jl1.addElement(" ");
    
    jList1.setModel(jl1);//DefaultListModel of users in this chat
    
    //check for user respons every 5 seconds then shutdown executor
    exec2.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < Client.new_msgs.size(); i++) {
                if (Client.new_msgs.get(i).get_msg().equals(chatid + "true_newchat")&&Client.new_msgs.get(i).get_newchat()) {
                    jl1.removeElementAt(0);
                    jl1.addElement(Client.new_msgs.get(i).get_nickname());//add user nickname to the userlist of this chat
                    jTextArea1.append(Client.new_msgs.get(i).get_nickname() + " Connected to chat..!!!!"+ "\n");
                    Client.new_msgs.remove(i);
                    
                    jTextArea2.setText("");
                    jTextArea2.setEditable(true);
                    jButton3.setEnabled(true);
                    
                    exec2.shutdown();
                }
                else if(Client.new_msgs.get(i).get_msg().equals(chatid + "false_newchat")) {
                    jTextArea1.append(Client.new_msgs.get(i).get_nickname() + " Declined your request!!!!" + "\n");
                    jTextArea2.setText("");
                    Client.new_msgs.remove(i);
                    exec2.shutdown();
                }
            }
        }
    }, 0, 5, TimeUnit.SECONDS);
    
    //check for new messages for this chat every 5 seconds
    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < Client.new_msgs.size(); i++) {
                if (Client.new_msgs.get(i).get_chatid().equals(chatid)&&!Client.new_msgs.get(i).get_msg().equals(chatid + "true_newchat")&&!Client.new_msgs.get(i).get_msg().equals(chatid + "false_newchat")&&!Client.new_msgs.get(i).get_newchat()) {
                    //insert new message to jTextArea
                    jTextArea1.append(Client.new_msgs.get(i).get_nickname() + ": " + Client.new_msgs.get(i).get_msg() + "\n");
                    Client.new_msgs.remove(i);
                }
            }
        }
    }, 0, 5, TimeUnit.SECONDS);
}
 
Example 19
Project: uavstack   File: MonitorAgentUT.java   View Source Code Vote up 3 votes
public void initLineNumWriter() {

        LineNumberWriter lineWriter = new LineNumberWriter(curPath, list);

        ScheduledExecutorService scheduleWorker = Executors.newSingleThreadScheduledExecutor();

        scheduleWorker.scheduleAtFixedRate(lineWriter, 2000, 3000, TimeUnit.MILLISECONDS);

    }
 
Example 20
Project: swage   File: MXBeanPoller.java   View Source Code Vote up 3 votes
/**
 * Instantiates an MXBeanPoller.
 *
 * @param metricRecorder the metrics recorder to record measurements against
 * @param pollingIntervalSeconds the number of seconds between measurements. Must be positive.
 * @param sensors the set of sensors to measure at each interval
 */
public MXBeanPoller(final MetricRecorder metricRecorder,
                    final int pollingIntervalSeconds,
                    final List<Sensor> sensors)
{
    this(Executors.newSingleThreadScheduledExecutor(), metricRecorder, pollingIntervalSeconds, sensors);
}