java.util.concurrent.ScheduledExecutorService Java Examples

The following examples show how to use java.util.concurrent.ScheduledExecutorService. 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: TimeLimiterMethodInterceptor.java    From resilience4j with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings("unchecked")
public Object invokeForCompletionStage(MethodInvocation invocation,
                                       RecoveryFunction<?> fallbackMethod,
                                       io.github.resilience4j.timelimiter.TimeLimiter timeLimiter) {
    ScheduledExecutorService scheduler = Execution.current().getController().getExecutor();
    CompletableFuture<?> future = timeLimiter.executeCompletionStage(scheduler, () -> {
        try {
            return (CompletionStage) proceed(invocation);
        } catch (Throwable t) {
            final CompletableFuture<?> promise = new CompletableFuture<>();
            promise.completeExceptionally(t);
            return (CompletionStage) promise;
        }
    }).toCompletableFuture();
    completeFailedFuture(new TimeoutException(), fallbackMethod, future);
    return future;
}
 
Example #2
Source File: SchedulerExecutorTest2.java    From java-core-learning-example with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
        SchedulerExecutorTest2 executor = new SchedulerExecutorTest2("job1");
        // 获取当前时间
        Calendar currentDate = Calendar.getInstance();
        long currentDateLong = currentDate.getTime().getTime();
        System.out.println("Current Date = " + currentDate.getTime().toString());
        // 计算满足条件的最近一次执行时间
        Calendar earliestDate = executor.getEarliestDate(currentDate,3,16,38,10);
        long earliestDateLong = earliestDate.getTime().getTime();
        System.out.println("Earliest Date = " + earliestDate.getTime().toString());
        // 计算从当前时间到最近一次执行时间的时间间隔
        long delay = earliestDateLong - currentDateLong;
        // 计算执行周期为一星期
//        long period = 7 * 24 * 60 * 60 * 1000;
        long period = 1000;
        ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
        // 从现在开始delay毫秒之后,每隔一星期执行一次job1
        service.scheduleAtFixedRate(executor, delay, period,
                TimeUnit.MILLISECONDS);
    }
 
Example #3
Source File: MarkdownManager.java    From das with Apache License 2.0 6 votes vote down vote up
public static void init() {
	if(managerRef.get() !=null) {
           return;
       }
	
	synchronized (MarkdownManager.class) {
		if(managerRef.get() !=null) {
               return;
           }
		
		ArrayList<ErrorDetector> detectors = new ArrayList<ErrorDetector>();
		// We currently only have Timeout case
		detectors.add(new TimeoutDetector());

		detectorsRef.set(detectors);
		ScheduledExecutorService manager = new ScheduledThreadPoolExecutor(1);
		manager.scheduleAtFixedRate(new CollectExceptionTask(), durations,
				durations, TimeUnit.MICROSECONDS);

		managerRef.set(manager);
	}
}
 
Example #4
Source File: Spouts.java    From cyclops with Apache License 2.0 6 votes vote down vote up
static  ReactiveSeq<Integer> interval(String cron,ScheduledExecutorService exec) {
    ReactiveSubscriber<Integer> sub = reactiveSubscriber();
    AtomicBoolean isOpen = new AtomicBoolean(true);
    Subscription[] s= {null};
    sub.onSubscribe(new Subscription() {
        @Override
        public void request(long n) {
            s[0].request(n);
        }

        @Override
        public void cancel() {
            isOpen.set(false);
        }
    });

    s[0] = ReactiveSeq.iterate(1, a -> a + 1)
                      .takeWhile(e -> isOpen.get())
                      .schedule(cron, exec)
                      .connect()
                      .forEach(1, e -> sub.onNext(e));

    return sub.reactiveStream();

}
 
Example #5
Source File: PravegaTablesStoreHelper.java    From pravega with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
PravegaTablesStoreHelper(SegmentHelper segmentHelper, GrpcAuthHelper authHelper, ScheduledExecutorService executor, int numOfRetries) {
    this.segmentHelper = segmentHelper;
    this.executor = executor;

    cache = new Cache(x -> {
        TableCacheKey<?> entryKey = (TableCacheKey<?>) x;

        // Since there are be multiple tables, we will cache `table+key` in our cache
        return getEntry(entryKey.getTable(), entryKey.getKey(), entryKey.fromBytesFunc)
                .thenApply(v -> new VersionedMetadata<>(v.getObject(), v.getVersion()));
    });
    this.authHelper = authHelper;
    this.authToken = new AtomicReference<>(authHelper.retrieveMasterToken());
    this.numOfRetries = numOfRetries;
}
 
Example #6
Source File: ScheduledExecutorServiceTest.java    From threadly with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void futureCancelTest() throws InterruptedException, ExecutionException {
  ScheduledExecutorService scheduler = makeScheduler(2);
  BlockingTestRunnable btr = new BlockingTestRunnable();
  try {
    final Future<?> f = scheduler.submit(btr);
    
    new Thread(new Runnable() {
      @Override
      public void run() {
        TestUtils.sleep(DELAY_TIME);
        f.cancel(true);
      }
    }).start();
    
    try {
      f.get();
      fail("exception should have been thrown");
    } catch (CancellationException e) {
      // expected
    }
  } finally {
    btr.unblock();
    scheduler.shutdownNow();
  }
}
 
Example #7
Source File: HBaseTimelineMetricsService.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
private void scheduleAggregatorThread(final TimelineMetricAggregator aggregator) {
  if (!aggregator.isDisabled()) {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(
      new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          return new Thread(r, ACTUAL_AGGREGATOR_NAMES.get(aggregator.getName()));
        }
      }
    );
    scheduledExecutors.put(aggregator.getName(), executorService);
    executorService.scheduleAtFixedRate(aggregator,
      0l,
      aggregator.getSleepIntervalMillis(),
      TimeUnit.MILLISECONDS);
    LOG.info("Scheduled aggregator thread " + aggregator.getName() + " every " +
      + aggregator.getSleepIntervalMillis() + " milliseconds.");
  } else {
    LOG.info("Skipped scheduling " + aggregator.getName() + " since it is disabled.");
  }
}
 
Example #8
Source File: TaskGroupsTest.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  storageUtil = new StorageTestUtil(this);
  storageUtil.expectOperations();
  ScheduledExecutorService executor = createMock(ScheduledExecutorService.class);
  clock = FakeScheduledExecutor.fromScheduledExecutorService(executor);
  backoffStrategy = createMock(BackoffStrategy.class);
  taskScheduler = createMock(TaskScheduler.class);
  rateLimiter = createMock(RateLimiter.class);
  rescheduleCalculator = createMock(RescheduleCalculator.class);
  batchWorker = createMock(TaskGroupBatchWorker.class);
  statsProvider = new FakeStatsProvider();
  taskGroups = new TaskGroups(
      executor,
      new TaskGroupsSettings(FIRST_SCHEDULE_DELAY, backoffStrategy, rateLimiter, 2),
      taskScheduler,
      rescheduleCalculator,
      batchWorker,
      statsProvider);
}
 
Example #9
Source File: PublisherFutureTest.java    From reactive-streams-commons with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 2000)
public void futureThrows() {
    ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
    try {
        Future<Integer> f = exec.schedule(() -> { throw new RuntimeException("forced failure"); }, 500, TimeUnit.MILLISECONDS);
        
        TestSubscriber<Integer> ts = new TestSubscriber<>();
        
        new PublisherFuture<>(f).subscribe(ts);
        
        ts.await();
        
        ts.assertNoValues()
        .assertError(ExecutionException.class)
        .assertErrorCause(RuntimeException.class)
        .assertNotComplete();
        
    } finally {
        exec.shutdown();
    }
}
 
Example #10
Source File: StorageImpl.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
public StorageImpl ( final File file, final BundleContext context, final DataFilePool pool, final ScheduledExecutorService queryExecutor, final ScheduledExecutorService updateExecutor, final ScheduledExecutorService eventExecutor ) throws Exception
{
    super ( file, pool, queryExecutor, eventExecutor );

    this.updateExecutor = updateExecutor;

    this.heartbeatJob = updateExecutor.scheduleAtFixedRate ( new Runnable () {
        @Override
        public void run ()
        {
            heartbeat ();
        }
    }, 0, getHeartbeatPeriod (), TimeUnit.MILLISECONDS );

    // register with OSGi
    final Dictionary<String, Object> properties = new Hashtable<String, Object> ( 2 );
    properties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );
    properties.put ( Constants.SERVICE_PID, this.id );
    this.handle = context.registerService ( StorageHistoricalItem.class, this, properties );
}
 
Example #11
Source File: TimedSemaphoreTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests the acquire() method if no limit is set. A test thread is started
 * that calls the semaphore a large number of times. Even if the semaphore's
 * period does not end, the thread should never block.
 */
@Test
public void testAcquireNoLimit() throws InterruptedException {
    final ScheduledExecutorService service = EasyMock
            .createMock(ScheduledExecutorService.class);
    final ScheduledFuture<?> future = EasyMock.createMock(ScheduledFuture.class);
    prepareStartTimer(service, future);
    EasyMock.replay(service, future);
    final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(service,
            PERIOD, UNIT, TimedSemaphore.NO_LIMIT);
    final int count = 1000;
    final CountDownLatch latch = new CountDownLatch(count);
    final SemaphoreThread t = new SemaphoreThread(semaphore, latch, count, count);
    t.start();
    latch.await();
    EasyMock.verify(service, future);
}
 
Example #12
Source File: StreamManagerImpl.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public StreamManagerImpl(String clientId,
                         DistributedLogConfiguration dlConfig,
                         ScheduledExecutorService executorService,
                         StreamFactory streamFactory,
                         StreamPartitionConverter partitionConverter,
                         StreamConfigProvider streamConfigProvider,
                         Namespace dlNamespace) {
    this.clientId = clientId;
    this.executorService = executorService;
    this.streamFactory = streamFactory;
    this.partitionConverter = partitionConverter;
    this.dlConfig = dlConfig;
    this.streamConfigProvider = streamConfigProvider;
    this.dlNamespace = dlNamespace;
}
 
Example #13
Source File: ScheduledTaskBeanLocatorTest.java    From bugsnag-java with MIT License 5 votes vote down vote up
@Test
public void findExecutorByName() {
    ScheduledExecutorService expected = Executors.newScheduledThreadPool(4);
    Throwable exc = new NoUniqueBeanDefinitionException(ScheduledExecutorService.class);
    when(context.getBean(ScheduledExecutorService.class)).thenThrow(exc);
    when(context.getBean("taskScheduler", ScheduledExecutorService.class))
            .thenReturn(expected);
    assertEquals(expected, beanLocator.resolveScheduledExecutorService());
}
 
Example #14
Source File: McgTask.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
private final static ScheduledExecutorService createScheduledExecutor() {

        final ScheduledExecutorService pool = new ScheduledThreadPoolExecutor(4, new WontonThreadFactory("wonton-monitor", true));

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                pool.shutdown();
            }
        }, "mcg-task-ShutdownHook"));
        return pool;

    }
 
Example #15
Source File: TimerService.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public TimerService(
		final ScheduledExecutorService scheduledExecutorService,
		final long shutdownTimeout) {
	this.scheduledExecutorService = Preconditions.checkNotNull(scheduledExecutorService);

	Preconditions.checkArgument(shutdownTimeout >= 0L, "The shut down timeout must be larger than or equal than 0.");
	this.shutdownTimeout = shutdownTimeout;

	this.timeouts = new HashMap<>(16);
	this.timeoutListener = null;
}
 
Example #16
Source File: DelayRepeatTask.java    From indexr with Apache License 2.0 5 votes vote down vote up
static void doRunTask(DelayRepeatTask task, long delayMS, ScheduledExecutorService execSvr) {
    if (delayMS < 0) {
        task.onComplete();
    } else {
        execSvr.schedule(
                () -> doRunTask(task, task.run(), execSvr),
                delayMS,
                TimeUnit.MILLISECONDS);
    }
}
 
Example #17
Source File: TimedSemaphoreTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepares an executor service mock to expect the start of the timer.
 *
 * @param service the mock
 * @param future the future
 */
private void prepareStartTimer(final ScheduledExecutorService service,
        final ScheduledFuture<?> future) {
    service.scheduleAtFixedRate((Runnable) EasyMock.anyObject(), EasyMock
            .eq(PERIOD), EasyMock.eq(PERIOD), EasyMock.eq(UNIT));
    EasyMock.expectLastCall().andReturn(future);
}
 
Example #18
Source File: SpecServiceConfig.java    From feast with Apache License 2.0 5 votes vote down vote up
@Bean
public ScheduledExecutorService cachedSpecServiceScheduledExecutorService(
    CachedSpecService cachedSpecStorage) {
  ScheduledExecutorService scheduledExecutorService =
      Executors.newSingleThreadScheduledExecutor();
  // reload all specs including new ones periodically
  scheduledExecutorService.scheduleAtFixedRate(
      cachedSpecStorage::scheduledPopulateCache,
      CACHE_REFRESH_RATE_SECONDS,
      CACHE_REFRESH_RATE_SECONDS,
      TimeUnit.SECONDS);
  return scheduledExecutorService;
}
 
Example #19
Source File: RulePollerTest.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testPollerShutdown() {
    RulePoller poller = new RulePoller(client, new CentralizedManifest(), Clock.systemUTC());
    poller.start();
    poller.shutdown();

    ScheduledExecutorService executor = poller.getExecutor();
    assertThat(executor.isShutdown()).isTrue();
}
 
Example #20
Source File: ExecutionGraphDeploymentTest.java    From flink with Apache License 2.0 5 votes vote down vote up
private ExecutionGraph createExecutionGraph(Configuration configuration) throws Exception {
	final ScheduledExecutorService executor = TestingUtils.defaultExecutor();

	final JobID jobId = new JobID();
	final JobGraph jobGraph = new JobGraph(jobId, "test");
	jobGraph.setSnapshotSettings(
		new JobCheckpointingSettings(
			Collections.<JobVertexID>emptyList(),
			Collections.<JobVertexID>emptyList(),
			Collections.<JobVertexID>emptyList(),
			new CheckpointCoordinatorConfiguration(
				100,
				10 * 60 * 1000,
				0,
				1,
				CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION,
				false,
				false,
				0),
			null));

	final Time timeout = Time.seconds(10L);
	return ExecutionGraphBuilder.buildGraph(
		null,
		jobGraph,
		configuration,
		executor,
		executor,
		new ProgrammedSlotProvider(1),
		getClass().getClassLoader(),
		new StandaloneCheckpointRecoveryFactory(),
		timeout,
		new NoRestartStrategy(),
		new UnregisteredMetricsGroup(),
		blobWriter,
		timeout,
		LoggerFactory.getLogger(getClass()),
		NettyShuffleMaster.INSTANCE,
		NoOpPartitionTracker.INSTANCE);
}
 
Example #21
Source File: Issue75Test.java    From failsafe with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatFailSafeIsBrokenWithFallback() throws Exception {
  CircuitBreaker<Integer> breaker = new CircuitBreaker<Integer>().withFailureThreshold(10, 100).withSuccessThreshold(2).withDelay(
      Duration.ofMillis(100));
  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
  int result = Failsafe.with(Fallback.of(e -> 999), breaker)
      .with(service)
      .getStageAsync(() -> CompletableFuture.completedFuture(223))
      .get();

  Assert.assertEquals(result, 223);
}
 
Example #22
Source File: InProcessChannelBuilderTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void scheduledExecutorService_custom() {
  InProcessChannelBuilder builder = InProcessChannelBuilder.forName("foo");
  ScheduledExecutorService scheduledExecutorService =
      new FakeClock().getScheduledExecutorService();

  InProcessChannelBuilder builder1 = builder.scheduledExecutorService(scheduledExecutorService);
  assertSame(builder, builder1);

  ClientTransportFactory clientTransportFactory = builder1.buildTransportFactory();

  assertSame(scheduledExecutorService, clientTransportFactory.getScheduledExecutorService());

  clientTransportFactory.close();
}
 
Example #23
Source File: ThreadPoolTaskScheduler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
	ScheduledExecutorService executor = getScheduledExecutor();
	try {
		return executor.scheduleWithFixedDelay(errorHandlingTask(task, true), 0, delay, TimeUnit.MILLISECONDS);
	}
	catch (RejectedExecutionException ex) {
		throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
	}
}
 
Example #24
Source File: AbstractKeeperMasterChooserAlgorithm.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
public AbstractKeeperMasterChooserAlgorithm(String clusterId, String shardId, DcMetaCache dcMetaCache,
		CurrentMetaManager currentMetaManager, ScheduledExecutorService scheduled) {

	this.dcMetaCache = dcMetaCache;
	this.currentMetaManager = currentMetaManager;
	this.clusterId = clusterId;
	this.shardId = shardId;
	this.scheduled = scheduled;
}
 
Example #25
Source File: ServerMainModule.java    From presto with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@ForAsyncHttp
public static ScheduledExecutorService createAsyncHttpTimeoutExecutor(TaskManagerConfig config)
{
    return newScheduledThreadPool(config.getHttpTimeoutThreads(), daemonThreadsNamed("async-http-timeout-%s"));
}
 
Example #26
Source File: RestFunctionsTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void restGetShouldClose() throws Exception {
  RestFunctions.RestGet restGet = new RestFunctions.RestGet();
  CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
  ScheduledExecutorService executorService = mock(ScheduledExecutorService.class);

  RestFunctions.setCloseableHttpClient(httpClient);
  RestFunctions.setScheduledExecutorService(executorService);
  restGet.close();

  verify(httpClient, times(1)).close();
  verify(executorService, times(1)).shutdown();
  verifyNoMoreInteractions(httpClient);
}
 
Example #27
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Stops {@link #cleanupExecutor}.
 */
public static synchronized void shutdown() {
	CloverJMX instance = cloverJMX;
	if (instance != null) {
		ScheduledExecutorService executor = instance.cleanupExecutor;
		if (executor != null) {
			executor.shutdownNow();
		}
	}
}
 
Example #28
Source File: NextRTCConfig.java    From nextrtc-signaling-server with MIT License 5 votes vote down vote up
@Bean(name = Names.SCHEDULER_NAME)
public ScheduledExecutorService scheduler() {
    ScheduledExecutorFactoryBean factoryBean = new ScheduledExecutorFactoryBean();
    factoryBean.setThreadNamePrefix("NextRTCConfig");
    factoryBean.setPoolSize(properties.getSchedulerPoolSize());
    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}
 
Example #29
Source File: Job.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
protected ExecutorService startHeartbeat( final long intervalInSeconds ) {

    final ScheduledExecutorService heartbeat = Executors.newSingleThreadScheduledExecutor( new ThreadFactory() {

      @Override
      public Thread newThread( Runnable r ) {
        Thread thread = new Thread( r, "Job Heartbeat Thread for: " + getName() );
        thread.setDaemon( true );
        return thread;
      }
    } );

    heartbeat.scheduleAtFixedRate( new Runnable() {
      public void run() {

        if ( Job.this.isFinished() ) {
          log.logBasic( "Shutting down heartbeat signal for " + jobMeta.getName() );
          shutdownHeartbeat( heartbeat );
          return;
        }

        try {

          log.logDebug( "Triggering heartbeat signal for " + jobMeta.getName() + " at every " + intervalInSeconds
              + " seconds" );
          ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.JobHeartbeat.id, Job.this );

        } catch ( KettleException e ) {
          log.logError( e.getMessage(), e );
        }
      }
    }, intervalInSeconds /* initial delay */, intervalInSeconds /* interval delay */, TimeUnit.SECONDS );

    return heartbeat;
  }
 
Example #30
Source File: ProcessTest.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void test2 () throws Exception
{
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor ();

    final ProcessBuilder pb = new ProcessBuilder ( "sleep", "3" ); // FIXME: works only on unix
    final AbstractScheduledInput input = new ProcessInput ( executor, pb, Charset.forName ( "UTF-8" ), 1000 );

    final TestListener listener = new TestListener ();

    input.addInputListener ( listener );

    logger.debug ( "test2 - start" );

    input.start ();
    Thread.sleep ( 100 );
    logger.debug ( "test2 - stop" );
    input.stop ();
    logger.debug ( "test2 - dispose" );
    input.dispose ();

    logger.debug ( "test2 - shutdown" );
    executor.shutdown ();
    logger.debug ( "test2 - wait" );
    executor.awaitTermination ( Long.MAX_VALUE, TimeUnit.MINUTES );
    logger.debug ( "test2 - done" );

    dumpData ( listener );

    // TODO: test
}