当前位置: 首页>>代码示例>>Java>>正文


Java Executors.newSingleThreadScheduledExecutor方法代码示例

本文整理汇总了Java中java.util.concurrent.Executors.newSingleThreadScheduledExecutor方法的典型用法代码示例。如果您正苦于以下问题:Java Executors.newSingleThreadScheduledExecutor方法的具体用法?Java Executors.newSingleThreadScheduledExecutor怎么用?Java Executors.newSingleThreadScheduledExecutor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.Executors的用法示例。


在下文中一共展示了Executors.newSingleThreadScheduledExecutor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: scheduleClockUpdating

import java.util.concurrent.Executors; //导入方法依赖的package包/类
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);
}
 
开发者ID:y123456yz,项目名称:reading-and-annotate-rocketmq-3.4.6,代码行数:17,代码来源:SystemClock.java

示例2: contextInitialized

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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);
        }

    }
 
开发者ID:openNaEF,项目名称:openNaEF,代码行数:26,代码来源:Notifier.java

示例3: buildCoapMessaging

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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;
}
 
开发者ID:ARMmbed,项目名称:java-coap,代码行数:23,代码来源:CoapServerBuilder.java

示例4: sendMsg

import java.util.concurrent.Executors; //导入方法依赖的package包/类
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);
    }
 
开发者ID:wanghan0501,项目名称:WiFiProbeAnalysis,代码行数:11,代码来源:Monitor.java

示例5: doStart

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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();
}
 
开发者ID:DevOpsStudio,项目名称:Re-Collector,代码行数:21,代码来源:MemoryReporterService.java

示例6: start

import java.util.concurrent.Executors; //导入方法依赖的package包/类
/**
 * 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);
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:27,代码来源:GangliaServer.java

示例7: testDuplicationAfterCleanUpTimeout

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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();
    }
}
 
开发者ID:ARMmbed,项目名称:java-coap,代码行数:24,代码来源:DuplicationDetectorTest.java

示例8: triggerCheckpoint

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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;
}
 
开发者ID:pravega,项目名称:flink-connectors,代码行数:26,代码来源:ReaderCheckpointHook.java

示例9: NodeManager

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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);
    }
}
 
开发者ID:talentchain,项目名称:talchain,代码行数:28,代码来源:NodeManager.java

示例10: Countly

import java.util.concurrent.Executors; //导入方法依赖的package包/类
/**
 * 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);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:16,代码来源:Countly.java

示例11: start

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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 );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:9,代码来源:Activator.java

示例12: scheduleClockUpdating

import java.util.concurrent.Executors; //导入方法依赖的package包/类
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);
}
 
开发者ID:youngMen1,项目名称:-Spring-SpringMVC-Mybatis-,代码行数:15,代码来源:SystemClock.java

示例13: testReschedule

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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);
}
 
开发者ID:nsg-ethz,项目名称:iTAP-controller,代码行数:47,代码来源:SingletonTaskTest.java

示例14: AutoReconnectController

import java.util.concurrent.Executors; //导入方法依赖的package包/类
/**
 * 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 );
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:44,代码来源:AutoReconnectController.java

示例15: configure

import java.util.concurrent.Executors; //导入方法依赖的package包/类
@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
	);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:61,代码来源:DriverManagerConnectionProviderImpl.java


注:本文中的java.util.concurrent.Executors.newSingleThreadScheduledExecutor方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。