Example usage for org.springframework.scheduling.support PeriodicTrigger PeriodicTrigger

List of usage examples for org.springframework.scheduling.support PeriodicTrigger PeriodicTrigger

Introduction

In this page you can find the example usage for org.springframework.scheduling.support PeriodicTrigger PeriodicTrigger.

Prototype

public PeriodicTrigger(long period) 

Source Link

Document

Create a trigger with the given period in milliseconds.

Usage

From source file:com.apress.prospringintegration.endpoints.pollingconsumer.Main.java

public static void main(String[] args) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "polling-consumer.xml");
    applicationContext.start();/* www . j av a  2 s  .  c o m*/

    ProblemReporter problemReporter = applicationContext.getBean(ProblemReporter.class);
    TicketMessageHandler ticketMessageHandler = applicationContext.getBean(TicketMessageHandler.class);
    TicketGenerator ticketGenerator = applicationContext.getBean(TicketGenerator.class);

    QueueChannel channel = applicationContext.getBean("ticketChannel", QueueChannel.class);

    // Define the polling consumer
    PollingConsumer ticketConsumer = new PollingConsumer(channel, ticketMessageHandler);
    ticketConsumer.setReceiveTimeout(RECEIVE_TIMEOUT);
    ticketConsumer.setBeanFactory(applicationContext);

    // Setup the poller using periodic trigger
    PeriodicTrigger periodicTrigger = new PeriodicTrigger(1000);
    periodicTrigger.setInitialDelay(5000);
    periodicTrigger.setFixedRate(false);

    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(periodicTrigger);
    pollerMetadata.setMaxMessagesPerPoll(3);

    ticketConsumer.setPollerMetadata(pollerMetadata);

    // Starts the polling consumer in the other thread
    ticketConsumer.start();

    // Generates messages and sends to the channel
    List<Ticket> tickets = ticketGenerator.createTickets();
    while (true) {
        for (Ticket ticket : tickets) {
            problemReporter.openTicket(ticket);
        }
    }
}

From source file:nhs.spring.integration.App.java

public static void main(String... args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "spring-integration-context.xml");
    GameMessageHandler gameHandler = new GameMessageHandler();
    GameGenerator gameGenerator = context.getBean(GameGenerator.class);

    context.start();//from   w  w  w .  ja v a2s.c  o  m

    //MessageChannel input = context.getBean("input-channel", MessageChannel.class);
    //PollableChannel output = context.getBean("output-channel", PollableChannel.class);
    QueueChannel qChannel = context.getBean("game-channel", QueueChannel.class);

    PollingConsumer gameConsumer = new PollingConsumer(qChannel, gameHandler);
    gameConsumer.setReceiveTimeout(RECEIVE_TIMEOUT);
    gameConsumer.setBeanFactory(context);

    // Set up the poller using periodic trigger
    PeriodicTrigger periodicTrigger = new PeriodicTrigger(1000);
    periodicTrigger.setInitialDelay(5000);
    periodicTrigger.setFixedRate(false);

    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(periodicTrigger);
    pollerMetadata.setMaxMessagesPerPoll(3);

    gameConsumer.setPollerMetadata(pollerMetadata);

    // Starts the polling consumer in the other thread
    gameConsumer.start();

    Date today = new Date();

    // Generates messages and sends to the channel
    Game game = gameGenerator.generateGame("League of legend", "Riot Games", today, "Tom", "Michael", "AOS");

    qChannel.send(MessageBuilder.withPayload(game).build());

    /*
    PublishSubscribeChannel pubsubChannel = null;
            
    pubsubChannel.subscribe(gameHandler);
            
    input.send(MessageBuilder.withPayload("Spring Integration / Hello NHS").build());
    Message<?> reply = output.receive();
            
    System.out.println("Received :" + reply);
    */
}

From source file:com.create.application.configuration.IntegrationConfiguration.java

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata defaultPoller() {
    final PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(new PeriodicTrigger(10));
    return pollerMetadata;
}

From source file:hello.CrawlerApp.java

@Bean
public PollerMetadata downloadTrigger() {
    PeriodicTrigger trigger = new PeriodicTrigger(config.getDownloadInterval());
    trigger.setFixedRate(true);/*from  ww w.  j  av a 2  s  . c  om*/
    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(trigger);
    pollerMetadata.setMaxMessagesPerPoll(1);
    return pollerMetadata;
}

From source file:hello.CrawlerApp.java

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata poller() {
    PeriodicTrigger trigger = new PeriodicTrigger(10);
    trigger.setFixedRate(true);/* www.java 2s  .c  om*/
    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(trigger);
    return pollerMetadata;
}

From source file:io.spring.batch.configuration.JobConfiguration.java

@Bean(name = PollerMetadata.DEFAULT_POLLER)
public PollerMetadata defaultPoller() {
    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(new PeriodicTrigger(10));
    return pollerMetadata;
}

From source file:org.springframework.data.hadoop.store.support.PollingTaskSupport.java

/**
 * Instantiates a new polling task support. On default a simple {@code PeriodicTrigger} is used.
 *
 * @param taskScheduler the task scheduler
 * @param taskExecutor the task executor
 * @param unit the unit/*from w w  w.j av a  2  s  .  c  o  m*/
 * @param duration the duration
 */
public PollingTaskSupport(TaskScheduler taskScheduler, TaskExecutor taskExecutor, TimeUnit unit,
        long duration) {
    this.taskScheduler = taskScheduler;
    this.taskExecutor = taskExecutor;
    this.trigger = new PeriodicTrigger(unit.toMillis(duration));
}

From source file:org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.java

protected void configurePollingEndpoint(AbstractPollingEndpoint pollingEndpoint, List<Annotation> annotations) {
    PollerMetadata pollerMetadata = null;
    Poller[] pollers = MessagingAnnotationUtils.resolveAttribute(annotations, "poller", Poller[].class);
    if (!ObjectUtils.isEmpty(pollers)) {
        Assert.state(pollers.length == 1,
                "The 'poller' for an Annotation-based endpoint can have only one '@Poller'.");
        Poller poller = pollers[0];//from w  w w  .j  av  a  2s .c  o m

        String ref = poller.value();
        String triggerRef = poller.trigger();
        String executorRef = poller.taskExecutor();
        String fixedDelayValue = this.beanFactory.resolveEmbeddedValue(poller.fixedDelay());
        String fixedRateValue = this.beanFactory.resolveEmbeddedValue(poller.fixedRate());
        String maxMessagesPerPollValue = this.beanFactory.resolveEmbeddedValue(poller.maxMessagesPerPoll());
        String cron = this.beanFactory.resolveEmbeddedValue(poller.cron());
        String errorChannel = this.beanFactory.resolveEmbeddedValue(poller.errorChannel());

        if (StringUtils.hasText(ref)) {
            Assert.state(!StringUtils.hasText(triggerRef) && !StringUtils.hasText(executorRef)
                    && !StringUtils.hasText(cron) && !StringUtils.hasText(fixedDelayValue)
                    && !StringUtils.hasText(fixedRateValue) && !StringUtils.hasText(maxMessagesPerPollValue),
                    "The '@Poller' 'ref' attribute is mutually exclusive with other attributes.");
            pollerMetadata = this.beanFactory.getBean(ref, PollerMetadata.class);
        } else {
            pollerMetadata = new PollerMetadata();
            if (StringUtils.hasText(maxMessagesPerPollValue)) {
                pollerMetadata.setMaxMessagesPerPoll(Long.parseLong(maxMessagesPerPollValue));
            } else if (pollingEndpoint instanceof SourcePollingChannelAdapter) {
                // SPCAs default to 1 message per poll
                pollerMetadata.setMaxMessagesPerPoll(1);
            }

            if (StringUtils.hasText(executorRef)) {
                pollerMetadata.setTaskExecutor(this.beanFactory.getBean(executorRef, TaskExecutor.class));
            }

            Trigger trigger = null;
            if (StringUtils.hasText(triggerRef)) {
                Assert.state(
                        !StringUtils.hasText(cron) && !StringUtils.hasText(fixedDelayValue)
                                && !StringUtils.hasText(fixedRateValue),
                        "The '@Poller' 'trigger' attribute is mutually exclusive with other attributes.");
                trigger = this.beanFactory.getBean(triggerRef, Trigger.class);
            } else if (StringUtils.hasText(cron)) {
                Assert.state(!StringUtils.hasText(fixedDelayValue) && !StringUtils.hasText(fixedRateValue),
                        "The '@Poller' 'cron' attribute is mutually exclusive with other attributes.");
                trigger = new CronTrigger(cron);
            } else if (StringUtils.hasText(fixedDelayValue)) {
                Assert.state(!StringUtils.hasText(fixedRateValue),
                        "The '@Poller' 'fixedDelay' attribute is mutually exclusive with other attributes.");
                trigger = new PeriodicTrigger(Long.parseLong(fixedDelayValue));
            } else if (StringUtils.hasText(fixedRateValue)) {
                trigger = new PeriodicTrigger(Long.parseLong(fixedRateValue));
                ((PeriodicTrigger) trigger).setFixedRate(true);
            }
            //'Trigger' can be null. 'PollingConsumer' does fallback to the 'new PeriodicTrigger(10)'.
            pollerMetadata.setTrigger(trigger);

            if (StringUtils.hasText(errorChannel)) {
                MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler();
                errorHandler.setDefaultErrorChannelName(errorChannel);
                errorHandler.setBeanFactory(this.beanFactory);
                pollerMetadata.setErrorHandler(errorHandler);
            }
        }
    } else {
        pollerMetadata = PollerMetadata.getDefaultPollerMetadata(this.beanFactory);
        Assert.notNull(pollerMetadata, "No poller has been defined for Annotation-based endpoint, "
                + "and no default poller is available within the context.");
    }
    pollingEndpoint.setTaskExecutor(pollerMetadata.getTaskExecutor());
    pollingEndpoint.setTrigger(pollerMetadata.getTrigger());
    pollingEndpoint.setAdviceChain(pollerMetadata.getAdviceChain());
    pollingEndpoint.setMaxMessagesPerPoll(pollerMetadata.getMaxMessagesPerPoll());
    pollingEndpoint.setErrorHandler(pollerMetadata.getErrorHandler());
    if (pollingEndpoint instanceof PollingConsumer) {
        ((PollingConsumer) pollingEndpoint).setReceiveTimeout(pollerMetadata.getReceiveTimeout());
    }
    pollingEndpoint.setTransactionSynchronizationFactory(pollerMetadata.getTransactionSynchronizationFactory());
}

From source file:org.springframework.integration.config.SourcePollingChannelAdapterFactoryBeanTests.java

@Test
public void testAdviceChain() throws Exception {
    SourcePollingChannelAdapterFactoryBean factoryBean = new SourcePollingChannelAdapterFactoryBean();
    QueueChannel outputChannel = new QueueChannel();
    TestApplicationContext context = TestUtils.createTestApplicationContext();
    factoryBean.setBeanFactory(context.getBeanFactory());
    factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
    factoryBean.setOutputChannel(outputChannel);
    factoryBean.setSource(() -> new GenericMessage<>("test"));
    PollerMetadata pollerMetadata = new PollerMetadata();
    List<Advice> adviceChain = new ArrayList<Advice>();
    final AtomicBoolean adviceApplied = new AtomicBoolean(false);
    adviceChain.add((MethodInterceptor) invocation -> {
        adviceApplied.set(true);/*from   w w  w .  j a va 2 s.c o m*/
        return invocation.proceed();
    });
    pollerMetadata.setTrigger(new PeriodicTrigger(5000));
    pollerMetadata.setMaxMessagesPerPoll(1);
    pollerMetadata.setAdviceChain(adviceChain);
    factoryBean.setPollerMetadata(pollerMetadata);
    factoryBean.setAutoStartup(true);
    factoryBean.afterPropertiesSet();
    context.registerEndpoint("testPollingEndpoint", factoryBean.getObject());
    context.refresh();
    Message<?> message = outputChannel.receive(5000);
    assertEquals("test", message.getPayload());
    assertTrue("adviceChain was not applied", adviceApplied.get());
}

From source file:org.springframework.integration.config.SourcePollingChannelAdapterFactoryBeanTests.java

@Test
public void testTransactionalAdviceChain() throws Throwable {
    SourcePollingChannelAdapterFactoryBean factoryBean = new SourcePollingChannelAdapterFactoryBean();
    QueueChannel outputChannel = new QueueChannel();
    TestApplicationContext context = TestUtils.createTestApplicationContext();
    factoryBean.setBeanFactory(context.getBeanFactory());
    factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
    factoryBean.setOutputChannel(outputChannel);
    factoryBean.setSource(() -> new GenericMessage<>("test"));
    PollerMetadata pollerMetadata = new PollerMetadata();
    List<Advice> adviceChain = new ArrayList<Advice>();
    final AtomicBoolean adviceApplied = new AtomicBoolean(false);
    adviceChain.add((MethodInterceptor) invocation -> {
        adviceApplied.set(true);/*from  w  w  w. j  ava 2  s. c o  m*/
        return invocation.proceed();
    });
    pollerMetadata.setTrigger(new PeriodicTrigger(5000));
    pollerMetadata.setMaxMessagesPerPoll(1);
    final AtomicInteger count = new AtomicInteger();
    final MethodInterceptor txAdvice = mock(MethodInterceptor.class);
    adviceChain.add((MethodInterceptor) invocation -> {
        count.incrementAndGet();
        return invocation.proceed();
    });
    when(txAdvice.invoke(any(MethodInvocation.class))).thenAnswer(invocation -> {
        count.incrementAndGet();
        return ((MethodInvocation) invocation.getArgument(0)).proceed();
    });

    pollerMetadata.setAdviceChain(adviceChain);
    factoryBean.setPollerMetadata(pollerMetadata);
    factoryBean.setAutoStartup(true);
    factoryBean.afterPropertiesSet();
    context.registerEndpoint("testPollingEndpoint", factoryBean.getObject());
    context.refresh();
    Message<?> message = outputChannel.receive(5000);
    assertEquals("test", message.getPayload());
    assertEquals(1, count.get());
    assertTrue("adviceChain was not applied", adviceApplied.get());
}