Java Code Examples for org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler#initialize()

The following examples show how to use org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler#initialize() . 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: StompTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
    log.info("=============================={}.{}==============================",
            this.getClass().getSimpleName(),
            this.testName.getMethodName());

    String brokerStomp = "ws://localhost:" + this.listenPort + "/weevent-broker/stomp";
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();

    this.stompClient = new WebSocketStompClient(new StandardWebSocketClient());

    // MappingJackson2MessageConverter
    stompClient.setMessageConverter(new StringMessageConverter());
    stompClient.setTaskScheduler(taskScheduler); // for heartbeats

    this.header.setDestination(topic);
    this.header.set("eventId", WeEvent.OFFSET_LAST);
    this.header.set("groupId", WeEvent.DEFAULT_GROUP_ID);

    this.failure = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    this.stompSession = this.stompClient.connect(brokerStomp, new MyStompSessionHandler(latch, this.failure)).get();
    latch.await();
    this.stompSession.setAutoReceipt(true);
}
 
Example 2
Source File: BeanRegistrarIT.java    From spring-batch-lightmin with Apache License 2.0 6 votes vote down vote up
@Test
public void registerPeriodSchedulerIT() {
    final JobSchedulerConfiguration jobSchedulerConfiguration = DomainTestHelper.createJobSchedulerConfiguration(null,
            10L, 10L, JobSchedulerType.PERIOD);
    final JobConfiguration jobConfiguration = DomainTestHelper.createJobConfiguration(jobSchedulerConfiguration);
    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    final SchedulerConstructorWrapper schedulerConstructorWrapper = new SchedulerConstructorWrapper();
    schedulerConstructorWrapper.setJob(this.simpleJob);
    schedulerConstructorWrapper.setJobConfiguration(jobConfiguration);
    schedulerConstructorWrapper.setJobIncrementer(JobIncrementer.DATE);
    schedulerConstructorWrapper.setJobLauncher(this.jobLauncher);
    schedulerConstructorWrapper.setJobParameters(new JobParametersBuilder().toJobParameters());
    schedulerConstructorWrapper.setThreadPoolTaskScheduler(scheduler);
    final Set<Object> constructorValues = new HashSet<>();
    constructorValues.add(schedulerConstructorWrapper);
    this.beanRegistrar
            .registerBean(PeriodScheduler.class, "sampleBeanRegistrar", constructorValues, null, null, null, null);
    final PeriodScheduler periodScheduler = this.applicationContext.getBean("sampleBeanRegistrar", PeriodScheduler
            .class);
    assertThat(periodScheduler).isNotNull();
    periodScheduler.schedule();
    this.applicationContext.close();
}
 
Example 3
Source File: PingWatchdogManagerTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws InterruptedException {

  ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
  executor.initialize();

  NativeSessionCloser closer = mock(NativeSessionCloser.class);
  PingWatchdogManager manager = new PingWatchdogManager(executor, closer);

  manager.setPingWatchdog(true);

  for (int i = 0; i < 10; i++) {
    manager.pingReceived("TransportID", 100);
    Thread.sleep(100);
  }

  Thread.sleep(500);

  verify(closer).closeSession("TransportID");
}
 
Example 4
Source File: HeartBeatCommand.java    From genie with Apache License 2.0 6 votes vote down vote up
@Override
public ExitCode run() {

    final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(1);
    scheduler.initialize();
    scheduler.scheduleAtFixedRate(this::checkConnectionStatus, 1000);

    final String pseudoJobId = this.getClass().getSimpleName() + UUID.randomUUID().toString();

    System.out.println("Initiating protocol with pseudo jobId: " + pseudoJobId);

    agentHeartBeatService.start(pseudoJobId);

    synchronized (this) {
        try {
            wait(TimeUnit.MILLISECONDS.convert(heartBeatCommandArguments.getRunDuration(), TimeUnit.SECONDS));
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted");
        }
    }

    agentHeartBeatService.stop();

    return ExitCode.SUCCESS;
}
 
Example 5
Source File: StackdriverTraceAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "traceExecutorProvider")
public ExecutorProvider traceExecutorProvider(GcpTraceProperties traceProperties, @Qualifier("traceSenderThreadPool") Optional<ThreadPoolTaskScheduler> userProvidedScheduler) {
	ThreadPoolTaskScheduler scheduler;
	if (userProvidedScheduler.isPresent()) {
		scheduler = userProvidedScheduler.get();
	}
	else {
		this.defaultTraceSenderThreadPool = new ThreadPoolTaskScheduler();
		scheduler = this.defaultTraceSenderThreadPool;
		scheduler.setPoolSize(traceProperties.getNumExecutorThreads());
		scheduler.setThreadNamePrefix("gcp-trace-sender");
		scheduler.setDaemon(true);
		scheduler.initialize();
	}
	return FixedExecutorProvider.create(scheduler.getScheduledExecutor());
}
 
Example 6
Source File: SchedulerConfig.java    From code-examples with MIT License 5 votes vote down vote up
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();

    scheduler.setPoolSize(POOL_SIZE);
    scheduler.setThreadNamePrefix("My-Scheduler-");
    scheduler.initialize();

    taskRegistrar.setTaskScheduler(scheduler);
}
 
Example 7
Source File: AgentAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Provide a lazy {@link TaskScheduler} bean for use by the heart beat service is none has already been
 * defined in the context.
 *
 * @return A {@link TaskScheduler} that the heart beat service should use
 */
@Bean
@Lazy
@ConditionalOnMissingBean(name = "heartBeatServiceTaskScheduler")
public TaskScheduler heartBeatServiceTaskScheduler() {
    final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setPoolSize(1);
    taskScheduler.initialize();
    return taskScheduler;
}
 
Example 8
Source File: DatabaseMySQLTraceLogFlushHandler.java    From summerframework with Apache License 2.0 5 votes vote down vote up
public DatabaseMySQLTraceLogFlushHandler(DataSource dataSource) {
    Assert.notNull(dataSource, "DatabaseTraceLogFlushHandler must have dataSource.");
    this.dataSource = dataSource;
    doWithConnection(createTableIfNotExist);
    tableReady = true;
    threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setDaemon(true);
    threadPoolTaskScheduler.setThreadNamePrefix("TraceLogFlush");
    threadPoolTaskScheduler.initialize();
    threadPoolTaskScheduler.schedule(cleanerTask,
        new CronTrigger(System.getProperty("rabbit.trace.flush.trigger", "0 0 1 * * ?")));
}
 
Example 9
Source File: WebSocketAutoConfiguration.java    From graphql-spqr-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private TaskScheduler defaultTaskScheduler() {
    ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
    threadPoolScheduler.setThreadNamePrefix("GraphQLWSKeepAlive-");
    threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
    threadPoolScheduler.setRemoveOnCancelPolicy(true);
    threadPoolScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
    threadPoolScheduler.initialize();
    return threadPoolScheduler;
}
 
Example 10
Source File: SchedulerConfig.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the scheduler to allow multiple pools.
 *
 * @param taskRegistrar The task registrar.
 */
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

    threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
    threadPoolTaskScheduler.setThreadNamePrefix("scheduled-task-pool-");
    threadPoolTaskScheduler.initialize();

    taskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
 
Example 11
Source File: Issue410Tests.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
	ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
	executor.initialize();
	return executor;
}
 
Example 12
Source File: CronTriggerer.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Consumer<String> trigger) {
  scheduler = new ThreadPoolTaskScheduler();
  scheduler.initialize();
  scheduler.schedule(() -> trigger.accept("CRON"), new CronTrigger(cronExpression));
}
 
Example 13
Source File: TracedThreadPoolTaskSchedulerIntegrationTest.java    From java-spring-cloud with Apache License 2.0 4 votes vote down vote up
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
  final ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
  executor.initialize();
  return executor;
}
 
Example 14
Source File: BindingServiceTests.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
@Ignore
public void testLateBindingConsumer() throws Exception {
	BindingServiceProperties properties = new BindingServiceProperties();
	properties.setBindingRetryInterval(1);
	Map<String, BindingProperties> bindingProperties = new HashMap<>();
	BindingProperties props = new BindingProperties();
	props.setDestination("foo");
	final String inputChannelName = "input";
	bindingProperties.put(inputChannelName, props);
	properties.setBindings(bindingProperties);
	DefaultBinderFactory binderFactory = createMockBinderFactory();
	Binder binder = binderFactory.getBinder("mock", MessageChannel.class);
	ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
	scheduler.initialize();
	BindingService service = new BindingService(properties, binderFactory, scheduler);
	MessageChannel inputChannel = new DirectChannel();
	final Binding<MessageChannel> mockBinding = Mockito.mock(Binding.class);
	final CountDownLatch fail = new CountDownLatch(2);
	doAnswer(i -> {
		fail.countDown();
		if (fail.getCount() == 1) {
			throw new RuntimeException("fail");
		}
		return mockBinding;
	}).when(binder).bindConsumer(eq("foo"), isNull(), same(inputChannel),
			any(ConsumerProperties.class));
	Collection<Binding<MessageChannel>> bindings = service.bindConsumer(inputChannel,
			inputChannelName);
	assertThat(fail.await(10, TimeUnit.SECONDS)).isTrue();
	assertThat(bindings).hasSize(1);
	Binding<MessageChannel> delegate = TestUtils
			.getPropertyValue(bindings.iterator().next(), "delegate", Binding.class);
	int n = 0;
	while (n++ < 300 && delegate == null) {
		Thread.sleep(400);
	}
	assertThat(delegate).isSameAs(mockBinding);
	service.unbindConsumers(inputChannelName);
	verify(binder, times(2)).bindConsumer(eq("foo"), isNull(), same(inputChannel),
			any(ConsumerProperties.class));
	verify(delegate).unbind();
	binderFactory.destroy();
}
 
Example 15
Source File: ConfigWatch.java    From spring-cloud-consul with Apache License 2.0 4 votes vote down vote up
private static ThreadPoolTaskScheduler getTaskScheduler() {
	ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
	taskScheduler.initialize();
	return taskScheduler;
}
 
Example 16
Source File: NacosWatch.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
private static ThreadPoolTaskScheduler getTaskScheduler() {
	ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
	taskScheduler.setBeanName("Nacso-Watch-Task-Scheduler");
	taskScheduler.initialize();
	return taskScheduler;
}
 
Example 17
Source File: BindingServiceTests.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testLateBindingProducer() throws Exception {
	BindingServiceProperties properties = new BindingServiceProperties();
	properties.setBindingRetryInterval(1);
	Map<String, BindingProperties> bindingProperties = new HashMap<>();
	BindingProperties props = new BindingProperties();
	props.setDestination("foo");
	final String outputChannelName = "output";
	bindingProperties.put(outputChannelName, props);
	properties.setBindings(bindingProperties);
	DefaultBinderFactory binderFactory = createMockBinderFactory();
	Binder binder = binderFactory.getBinder("mock", MessageChannel.class);
	ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
	scheduler.initialize();
	BindingService service = new BindingService(properties, binderFactory, scheduler);
	MessageChannel outputChannel = new DirectChannel();
	final Binding<MessageChannel> mockBinding = Mockito.mock(Binding.class);
	final CountDownLatch fail = new CountDownLatch(2);
	doAnswer(i -> {
		fail.countDown();
		if (fail.getCount() == 1) {
			throw new RuntimeException("fail");
		}
		return mockBinding;
	}).when(binder).bindProducer(eq("foo"), same(outputChannel),
			any(ProducerProperties.class));
	Binding<MessageChannel> binding = service.bindProducer(outputChannel,
			outputChannelName);
	assertThat(fail.await(10, TimeUnit.SECONDS)).isTrue();
	assertThat(binding).isNotNull();
	Binding delegate = TestUtils.getPropertyValue(binding, "delegate", Binding.class);
	int n = 0;
	while (n++ < 300 && delegate == null) {
		Thread.sleep(100);
		delegate = TestUtils.getPropertyValue(binding, "delegate", Binding.class);
	}
	assertThat(delegate).isSameAs(mockBinding);
	service.unbindProducers(outputChannelName);
	verify(binder, times(2)).bindProducer(eq("foo"), same(outputChannel),
			any(ProducerProperties.class));
	verify(delegate).unbind();
	binderFactory.destroy();
	scheduler.destroy();
}
 
Example 18
Source File: TaskApplicationRunner.java    From train-ticket-reaper with MIT License 4 votes vote down vote up
@Override
public void run(ApplicationArguments var1) throws Exception {

    if (StringUtils.isEmpty(mode)) {
        mode = "1";
    }

    logger.info("您选择的模式为: " + mode);

    switch (mode) {
        case "1":
            ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
            threadPoolTaskScheduler.initialize();
            CronTrigger trigger = new CronTrigger("* * 6-23 * * ?");
            logger.info("使用 极速模式 开始抢票");
            threadPoolTaskScheduler.schedule(new Runnable() {
                @Override
                public void run() {
                    reaperService.monitor();
                }
            }, trigger);
            break;
        case "2":
            logger.info("使用 丧心病狂模式 开始抢票");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        reaperService.monitor();
                    }
                }
            }).start();
            break;
        case "3":
            logger.info("使用 为了抢票不要命模式 开始抢票");
            for (int i = 0; i < 100; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            reaperService.monitor();
                        }
                    }
                }).start();
            }
            break;
        case "4":
            logger.info("使用 无脑下单模式(不进行是否有票的监控,直接对符合要求的车次进行下单) 开始抢票");
            reaperService.noBrainPlaceOrder();
            break;
        default:
            logger.warn("不存在此模式 :" + mode + "  将退出程序");
            System.exit(1);
            break;
    }

    logger.info("火车票收割者,正常启动");
}
 
Example 19
Source File: ConfigWatch.java    From spring-cloud-formula with Apache License 2.0 4 votes vote down vote up
private ThreadPoolTaskScheduler getTaskScheduler() {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    return taskScheduler;
}
 
Example 20
Source File: ClusterSyncManagerLeaderListener.java    From Decision with Apache License 2.0 3 votes vote down vote up
private void initializeFailOverTask(){

        if (failOverTask!=null) {
            ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
            taskScheduler.initialize();

            taskScheduler.scheduleAtFixedRate(failOverTask, 60000);
        }

    }