Java Code Examples for java.util.concurrent.ScheduledThreadPoolExecutor#scheduleAtFixedRate()

The following examples show how to use java.util.concurrent.ScheduledThreadPoolExecutor#scheduleAtFixedRate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DelayOverflow.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void scheduleNow(ScheduledThreadPoolExecutor pool,
                 Runnable r, int how) {
    switch (how) {
    case 0:
        pool.schedule(r, 0, MILLISECONDS);
        break;
    case 1:
        pool.schedule(Executors.callable(r), 0, DAYS);
        break;
    case 2:
        pool.scheduleWithFixedDelay(r, 0, 1000, NANOSECONDS);
        break;
    case 3:
        pool.scheduleAtFixedRate(r, 0, 1000, MILLISECONDS);
        break;
    default:
        fail(String.valueOf(how));
    }
}
 
Example 2
Source File: ThreadPoolUtilTest.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Test
public void wrapException() {
	ScheduledThreadPoolExecutor executor = ThreadPoolBuilder.scheduledPool().build();
	ExceptionTask task = new ExceptionTask();
	executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS);

	ThreadUtil.sleep(500);

	// 线程第一次跑就被中断
	assertThat(task.counter.get()).isEqualTo(1);
	ThreadPoolUtil.gracefulShutdown(executor, 1000);

	////////
	executor = ThreadPoolBuilder.scheduledPool().build();
	ExceptionTask newTask = new ExceptionTask();
	Runnable wrapTask = ThreadPoolUtil.safeRunnable(newTask);
	executor.scheduleAtFixedRate(wrapTask, 0, 100, TimeUnit.MILLISECONDS);

	ThreadUtil.sleep(500);
	assertThat(newTask.counter.get()).isGreaterThan(2);
	System.out.println("-------actual run:" + task.counter.get());
	ThreadPoolUtil.gracefulShutdown(executor, 1000);

}
 
Example 3
Source File: ElasticApmTracerBuilder.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
private LifecycleListener scheduleReloadAtRate(final ConfigurationRegistry configurationRegistry, final int rate, TimeUnit seconds) {
    final ScheduledThreadPoolExecutor configurationReloader = ExecutorUtils.createSingleThreadSchedulingDeamonPool("configuration-reloader");
    configurationReloader.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            logger.debug("Beginning scheduled configuration reload (interval is {} sec)...", rate);
            configurationRegistry.reloadDynamicConfigurationOptions();
            logger.debug("Finished scheduled configuration reload");
        }
    }, rate, rate, seconds);
    return ClosableLifecycleListenerAdapter.of(new Closeable() {
        @Override
        public void close() {
            configurationReloader.shutdown();
        }
    });
}
 
Example 4
Source File: LockManager.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
public LockManager(RxSession session) {
    this.session = session;
    acquireLock = session.getSession().prepare(
            "UPDATE locks USING TTL ? SET value = ? WHERE name = ? IF value IN (NULL, ?)");
    releaseLock = session.getSession().prepare(
            "UPDATE locks SET value = NULL WHERE name = ? IF value = ?");
    renewLock = session.getSession().prepare(
            "UPDATE locks USING TTL ? SET value = ? WHERE name = ? IF value = ?");
    getTTL = session.getSession().prepare("SELECT TTL(value) FROM locks WHERE name = ?");

    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("locks-thread-pool-%d").build();
    locksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory, new ThreadPoolExecutor.DiscardPolicy());

    activeLocks = new HashMap<>();
    activeLocksLock = new ReentrantReadWriteLock();

    locksExecutor.scheduleAtFixedRate(this::renewLocks, 0, LOCK_RENEWAL_RATE, TimeUnit.SECONDS);
}
 
Example 5
Source File: ThreadPoolUtilTest.java    From vjtools with Apache License 2.0 6 votes vote down vote up
@Test
public void wrapException() {
	ScheduledThreadPoolExecutor executor = ThreadPoolBuilder.scheduledPool().build();
	ExceptionTask task = new ExceptionTask();
	executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS);

	ThreadUtil.sleep(500);

	// 线程第一次跑就被中断
	assertThat(task.counter.get()).isEqualTo(1);
	ThreadPoolUtil.gracefulShutdown(executor, 1000);

	////////
	executor = ThreadPoolBuilder.scheduledPool().build();
	ExceptionTask newTask = new ExceptionTask();
	Runnable wrapTask = ThreadPoolUtil.safeRunnable(newTask);
	executor.scheduleAtFixedRate(wrapTask, 0, 100, TimeUnit.MILLISECONDS);

	ThreadUtil.sleep(500);
	assertThat(newTask.counter.get()).isGreaterThan(2);
	System.out.println("-------actual run:" + task.counter.get());
	ThreadPoolUtil.gracefulShutdown(executor, 1000);

}
 
Example 6
Source File: ScheduledExecutorTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * scheduleAtFixedRate executes runnable after given initial delay
 */
public void testSchedule4() throws Exception {
    final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
    try (PoolCleaner cleaner = cleaner(p)) {
        final long startTime = System.nanoTime();
        final CountDownLatch done = new CountDownLatch(1);
        Runnable task = new CheckedRunnable() {
            public void realRun() {
                done.countDown();
                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
            }};
        ScheduledFuture f =
            p.scheduleAtFixedRate(task, timeoutMillis(),
                                  LONG_DELAY_MS, MILLISECONDS);
        await(done);
        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
        f.cancel(true);
    }
}
 
Example 7
Source File: PreferencesEntityStoreMixin.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
public void activateService()
    throws Exception
{
    root = getApplicationRoot();

    // Reload underlying store every 60 seconds
    reloadExecutor = new ScheduledThreadPoolExecutor( 1 );
    reloadExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy( false );
    reloadExecutor.scheduleAtFixedRate( () -> {
        try
        {
            //noinspection SynchronizeOnNonFinalField
            synchronized( root )
            {
                root.sync();
            }
        }
        catch( BackingStoreException e )
        {
            throw new EntityStoreException( "Could not reload preferences", e );
        }
    }, 0, 60, TimeUnit.SECONDS );
}
 
Example 8
Source File: ResponseCacher.java    From xipki with Apache License 2.0 5 votes vote down vote up
public void init() {
  updateCacheStore();

  scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
  scheduledThreadPoolExecutor.setRemoveOnCancelPolicy(true);

  // check every 600 seconds (10 minutes)
  this.responseCleaner = scheduledThreadPoolExecutor.scheduleAtFixedRate(
      new ExpiredResponsesCleaner(), 348, 600, TimeUnit.SECONDS);

  // check every 600 seconds (10 minutes)
  this.issuerUpdater = scheduledThreadPoolExecutor.scheduleAtFixedRate(
      new IssuerUpdater(), 448, 600, TimeUnit.SECONDS);
}
 
Example 9
Source File: ThreadPoolTest.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * 设置固定时间执行
 */
private static void newScheduledThreadPool2() {
	 ScheduledThreadPoolExecutor  exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10);   //创建大小为10的线程池  
	 long oneDay = 24 * 60 * 60 * 1000;    
	 long initDelay  = getTimeMillis("14:08:00") - System.currentTimeMillis();    
	 initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
	 exec.scheduleAtFixedRate(new MyThread2(String.valueOf(1)), initDelay, oneDay, TimeUnit.MILLISECONDS);
     System.out.println("运行结束!");
}
 
Example 10
Source File: ThreadPoolTest.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * 设置固定时间执行
 */
private static void newScheduledThreadPool2() {
	 ScheduledThreadPoolExecutor  exec = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10);   //创建大小为10的线程池  
	 long oneDay = 24 * 60 * 60 * 1000;    
	 long initDelay  = getTimeMillis("14:08:00") - System.currentTimeMillis();    
	 initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
	 exec.scheduleAtFixedRate(new MyThread(String.valueOf(1)), initDelay, oneDay, TimeUnit.MILLISECONDS);
     System.out.println("运行结束!");
}
 
Example 11
Source File: RedisSharedLock.java    From ecp-uid with Apache License 2.0 5 votes vote down vote up
@Override
public void startHeartBeatThread() {
    scheduledpool = new ScheduledThreadPoolExecutor(1, new NamingThreadFactory(Thread.currentThread().getName().concat(LOCK_HEART_BEAT), true));
    scheduledpool.scheduleAtFixedRate(() -> {
        redisTemplate.expire(lockKey, ttl, TimeUnit.MILLISECONDS);
        logger.debug(MSG_RELET, Thread.currentThread().getName(), lockKey);
    }, 0L, ttl / 3, TimeUnit.MILLISECONDS);
    
}
 
Example 12
Source File: StableRateLimiter.java    From locust4j with MIT License 5 votes vote down vote up
@Override
public void start() {
    updateTimer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("StableRateLimiter-bucket-updater");
            return thread;
        }
    });
    updateTimer.scheduleAtFixedRate(this, 0, period, unit);
    stopped.set(false);
}
 
Example 13
Source File: DataCenterInfoWatchdog.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("SendDataCenterInfo-schedule-pool-%d").daemon(true).build());
    scheduledExecutorService.scheduleAtFixedRate(() -> applicationEventPublisher.publishEvent(DataCenterInfoEvent.builder()
            .name(goPushDataCenterConfig.getName())
            .dataCenterInfo(watch())
            .build()), delay, delay, TimeUnit.MILLISECONDS);
}
 
Example 14
Source File: Maintainer.java    From vespa with Apache License 2.0 5 votes vote down vote up
public Maintainer(String name, Duration interval, Duration initialDelay, JobControl jobControl) {
    this.name = name;
    this.interval = requireInterval(interval);
    this.jobControl = Objects.requireNonNull(jobControl);
    service = new ScheduledThreadPoolExecutor(1, r -> new Thread(r, name() + "-worker"));
    service.scheduleAtFixedRate(this, initialDelay.toMillis(), interval.toMillis(), TimeUnit.MILLISECONDS);
    jobControl.started(name(), this);
}
 
Example 15
Source File: Lesson2.java    From Java-Concurrency-Multithreading-in-Practice with MIT License 5 votes vote down vote up
WeatherForecastPublisher() {
	super(Executors.newFixedThreadPool(2), Flow.defaultBufferSize());
	scheduler = new ScheduledThreadPoolExecutor(1);
	periodicTask = scheduler.scheduleAtFixedRate( //
			// runs submit()
			() -> submit(WeatherForecast.nextRandomWeatherForecast()), //
			500, 500, TimeUnit.MILLISECONDS);
}
 
Example 16
Source File: RemoteNodeManager.java    From lavaplayer with Apache License 2.0 4 votes vote down vote up
private void startScheduler(int initialSize) {
  ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(initialSize, new DaemonThreadFactory("remote"));
  scheduledExecutor.scheduleAtFixedRate(this, 2000, 2000, TimeUnit.MILLISECONDS);
  scheduler = scheduledExecutor;
}
 
Example 17
Source File: Stress.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Throwable {

        final CountDownLatch count = new CountDownLatch(1000);

        final ScheduledThreadPoolExecutor pool =
            new ScheduledThreadPoolExecutor(100);
        pool.prestartAllCoreThreads();

        final Runnable incTask = new Runnable() { public void run() {
            count.countDown();
        }};

        pool.scheduleAtFixedRate(incTask, 0, 10, TimeUnit.MILLISECONDS);

        count.await();

        pool.shutdown();
        pool.awaitTermination(1L, TimeUnit.DAYS);
    }
 
Example 18
Source File: TwitchPubSub.java    From twitch4j with MIT License 4 votes vote down vote up
/**
 * Constructor
 *
 * @param eventManager EventManager
 * @param taskExecutor ScheduledThreadPoolExecutor
 */
public TwitchPubSub(EventManager eventManager, ScheduledThreadPoolExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
    this.eventManager = eventManager;
    // register with serviceMediator
    this.eventManager.getServiceMediator().addService("twitch4j-pubsub", this);

    // connect
    this.connect();

    // Run heartbeat every 4 minutes
    heartbeatTask = taskExecutor.scheduleAtFixedRate(() -> {
        if (isClosed)
            return;

        PubSubRequest request = new PubSubRequest();
        request.setType(PubSubType.PING);
        sendCommand(TypeConvert.objectToJson(request));

        log.debug("PubSub: Sending PING!");
        lastPing = TimeUtils.getCurrentTimeInMillis();
    }, 0, 4L, TimeUnit.MINUTES);

    // queue command worker
    this.queueTask = taskExecutor.schedule(() -> {
        while (!isClosed) {
            try {
                // check for missing pong response
                if (TimeUtils.getCurrentTimeInMillis() >= lastPing + 10000 && lastPong < lastPing) {
                    log.warn("PubSub: Didn't receive a PONG response in time, reconnecting to obtain a connection to a different server.");
                    reconnect();
                }

                // If connected, send one message from the queue
                String command = commandQueue.poll(1000L, TimeUnit.MILLISECONDS);
                if (command != null) {
                    if (connectionState.equals(TMIConnectionState.CONNECTED)) {
                        sendCommand(command);
                        // Logging
                        log.debug("Processed command from queue: [{}].", command);
                    }
                }
            } catch (Exception ex) {
                log.error("PubSub: Unexpected error in worker thread", ex);
            }
        }
    }, 1L, TimeUnit.MILLISECONDS);

    log.debug("PubSub: Started Queue Worker Thread");
}
 
Example 19
Source File: ActorExecuterService.java    From actor4j-core with Apache License 2.0 4 votes vote down vote up
public void start(Runnable onStartup, Runnable onTermination) {
	if (system.cells.size()==0)
		return;
	
	int poolSize = Runtime.getRuntime().availableProcessors();
	
	globalTimerExecuterService = new ActorTimerExecuterService(system, 1, "actor4j-global-timer-thread");
	timerExecuterService = new ActorTimerExecuterService(system, poolSize);
	
	resourceExecuterService = new ThreadPoolExecutor(poolSize, maxResourceThreads, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), new DefaultThreadFactory("actor4j-resource-thread"));
	if (system.clientMode)
		clientExecuterService = Executors.newSingleThreadExecutor();
	
	if (system.persistenceMode) {
		persistenceService = new ActorPersistenceService(system.wrapper, system.parallelismMin, system.parallelismFactor, system.persistenceConnector);
		persistenceService.start();
	}
	
	this.onTermination = onTermination;
	
	actorThreadPool = new ActorThreadPool(system);
	
	podReplicationControllerExecuterService = new ScheduledThreadPoolExecutor(1, new DefaultThreadFactory("actor4j-replication-controller-thread"));
	try {
		Constructor<? extends PodReplicationControllerRunnable> constructor;
		constructor = system.podReplicationControllerRunnableClass.getConstructor(ActorSystemImpl.class);
		podReplicationControllerRunnable = constructor.newInstance(system);
	} catch (Exception e) {
		e.printStackTrace();
	}
	if (podReplicationControllerRunnable!=null)
		podReplicationControllerExecuterService.scheduleAtFixedRate(podReplicationControllerRunnable, system.horizontalPodAutoscalerSyncTime, system.horizontalPodAutoscalerSyncTime, TimeUnit.MILLISECONDS);
	
	/*
	 * necessary before executing onStartup; 
	 * creating of childrens in Actor::preStart: childrens needs to register at the dispatcher
	 * (see also ActorSystemImpl::internal_addCell)
	 */
	started.set(true);
	
	if (onStartup!=null)
		onStartup.run();
}
 
Example 20
Source File: WalletVersionManager.java    From nuls with MIT License 4 votes vote down vote up
public static void start() {
    ScheduledThreadPoolExecutor executor = TaskManager.createScheduledThreadPool(1, new NulsThreadFactory((short) 1, "version-manager"));
    executor.scheduleAtFixedRate(SyncVersionRunner.getInstance(), 0, 10, TimeUnit.MINUTES);
}