Search in sources :

Example 1 with Trigger

use of org.springframework.scheduling.Trigger in project spring-framework by spring-projects.

the class ScheduledAnnotationBeanPostProcessorTests method cronTaskWithZone.

@Test
public void cronTaskWithZone() throws InterruptedException {
    Assume.group(TestGroup.LONG_RUNNING);
    BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
    BeanDefinition targetDefinition = new RootBeanDefinition(CronWithTimezoneTestBean.class);
    context.registerBeanDefinition("postProcessor", processorDefinition);
    context.registerBeanDefinition("target", targetDefinition);
    context.refresh();
    Object postProcessor = context.getBean("postProcessor");
    Object target = context.getBean("target");
    ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar");
    @SuppressWarnings("unchecked") List<CronTask> cronTasks = (List<CronTask>) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks");
    assertEquals(1, cronTasks.size());
    CronTask task = cronTasks.get(0);
    ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable();
    Object targetObject = runnable.getTarget();
    Method targetMethod = runnable.getMethod();
    assertEquals(target, targetObject);
    assertEquals("cron", targetMethod.getName());
    assertEquals("0 0 0-4,6-23 * * ?", task.getExpression());
    Trigger trigger = task.getTrigger();
    assertNotNull(trigger);
    assertTrue(trigger instanceof CronTrigger);
    CronTrigger cronTrigger = (CronTrigger) trigger;
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+10"));
    cal.clear();
    // 15-04-2013 4:00 GMT+10
    cal.set(2013, 3, 15, 4, 0);
    Date lastScheduledExecutionTime = cal.getTime();
    Date lastActualExecutionTime = cal.getTime();
    // 4:30
    cal.add(Calendar.MINUTE, 30);
    Date lastCompletionTime = cal.getTime();
    TriggerContext triggerContext = new SimpleTriggerContext(lastScheduledExecutionTime, lastActualExecutionTime, lastCompletionTime);
    cal.add(Calendar.MINUTE, 30);
    // 6:00
    cal.add(Calendar.HOUR_OF_DAY, 1);
    Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
    // assert that 6:00 is next execution time
    assertEquals(cal.getTime(), nextExecutionTime);
    Thread.sleep(10000);
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger) CronTask(org.springframework.scheduling.config.CronTask) Calendar(java.util.Calendar) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) SimpleTriggerContext(org.springframework.scheduling.support.SimpleTriggerContext) Date(java.util.Date) ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable) Trigger(org.springframework.scheduling.Trigger) CronTrigger(org.springframework.scheduling.support.CronTrigger) ScheduledTaskRegistrar(org.springframework.scheduling.config.ScheduledTaskRegistrar) SimpleTriggerContext(org.springframework.scheduling.support.SimpleTriggerContext) TriggerContext(org.springframework.scheduling.TriggerContext) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) List(java.util.List) Test(org.junit.Test)

Example 2 with Trigger

use of org.springframework.scheduling.Trigger in project spring-integration by spring-projects.

the class AbstractMethodAnnotationPostProcessor method configurePollingEndpoint.

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];
        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());
}
Also used : TaskExecutor(org.springframework.core.task.TaskExecutor) CronTrigger(org.springframework.scheduling.support.CronTrigger) MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) Trigger(org.springframework.scheduling.Trigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) CronTrigger(org.springframework.scheduling.support.CronTrigger) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) PollerMetadata(org.springframework.integration.scheduling.PollerMetadata) Poller(org.springframework.integration.annotation.Poller) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger)

Example 3 with Trigger

use of org.springframework.scheduling.Trigger in project spring-integration by spring-projects.

the class PollerAdviceTests method testDefaultDontSkip.

@Test
public void testDefaultDontSkip() throws Exception {
    SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
    final CountDownLatch latch = new CountDownLatch(1);
    adapter.setSource(() -> {
        latch.countDown();
        return null;
    });
    adapter.setTrigger(new Trigger() {

        private boolean done;

        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            Date date = done ? null : new Date(System.currentTimeMillis() + 10);
            done = true;
            return date;
        }
    });
    configure(adapter);
    List<Advice> adviceChain = new ArrayList<Advice>();
    PollSkipAdvice advice = new PollSkipAdvice();
    adviceChain.add(advice);
    adapter.setAdviceChain(adviceChain);
    adapter.afterPropertiesSet();
    adapter.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    adapter.stop();
}
Also used : DynamicPeriodicTrigger(org.springframework.integration.util.DynamicPeriodicTrigger) OnlyOnceTrigger(org.springframework.integration.test.util.OnlyOnceTrigger) Trigger(org.springframework.scheduling.Trigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) CompoundTrigger(org.springframework.integration.util.CompoundTrigger) TriggerContext(org.springframework.scheduling.TriggerContext) ArrayList(java.util.ArrayList) PollSkipAdvice(org.springframework.integration.scheduling.PollSkipAdvice) SimpleActiveIdleMessageSourceAdvice(org.springframework.integration.aop.SimpleActiveIdleMessageSourceAdvice) CompoundTriggerAdvice(org.springframework.integration.aop.CompoundTriggerAdvice) AbstractMessageSourceAdvice(org.springframework.integration.aop.AbstractMessageSourceAdvice) Advice(org.aopalliance.aop.Advice) PollSkipAdvice(org.springframework.integration.scheduling.PollSkipAdvice) CountDownLatch(java.util.concurrent.CountDownLatch) Date(java.util.Date) Test(org.junit.Test)

Example 4 with Trigger

use of org.springframework.scheduling.Trigger in project spring-integration by spring-projects.

the class PollerAdviceTests method testCompoundTriggerAdvice.

@Test
public void testCompoundTriggerAdvice() throws Exception {
    SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
    final CountDownLatch latch = new CountDownLatch(5);
    final LinkedList<Object> overridePresent = new LinkedList<Object>();
    final CompoundTrigger compoundTrigger = new CompoundTrigger(new PeriodicTrigger(10));
    Trigger override = spy(new PeriodicTrigger(5));
    final CompoundTriggerAdvice advice = new CompoundTriggerAdvice(compoundTrigger, override);
    adapter.setSource(() -> {
        overridePresent.add(TestUtils.getPropertyValue(compoundTrigger, "override"));
        Message<Object> m = null;
        if (latch.getCount() % 2 == 0) {
            m = new GenericMessage<>("foo");
        }
        latch.countDown();
        return m;
    });
    adapter.setAdviceChain(Collections.singletonList(advice));
    adapter.setTrigger(compoundTrigger);
    configure(adapter);
    adapter.afterPropertiesSet();
    adapter.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    adapter.stop();
    while (overridePresent.size() > 5) {
        overridePresent.removeLast();
    }
    assertThat(overridePresent, contains(null, override, null, override, null));
    verify(override, atLeast(2)).nextExecutionTime(any(TriggerContext.class));
}
Also used : CompoundTrigger(org.springframework.integration.util.CompoundTrigger) DynamicPeriodicTrigger(org.springframework.integration.util.DynamicPeriodicTrigger) OnlyOnceTrigger(org.springframework.integration.test.util.OnlyOnceTrigger) Trigger(org.springframework.scheduling.Trigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) CompoundTrigger(org.springframework.integration.util.CompoundTrigger) TriggerContext(org.springframework.scheduling.TriggerContext) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) CompoundTriggerAdvice(org.springframework.integration.aop.CompoundTriggerAdvice) DynamicPeriodicTrigger(org.springframework.integration.util.DynamicPeriodicTrigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) Test(org.junit.Test)

Example 5 with Trigger

use of org.springframework.scheduling.Trigger in project spring-integration by spring-projects.

the class PollerAdviceTests method testMixedAdvice.

@Test
public void testMixedAdvice() throws Exception {
    SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
    final List<String> callOrder = new ArrayList<>();
    final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(4));
    MessageSource<Object> source = () -> {
        callOrder.add("c");
        latch.get().countDown();
        return null;
    };
    adapter.setSource(source);
    OnlyOnceTrigger trigger = new OnlyOnceTrigger();
    adapter.setTrigger(trigger);
    configure(adapter);
    List<Advice> adviceChain = new ArrayList<>();
    adviceChain.add((MethodInterceptor) invocation -> {
        callOrder.add("a");
        latch.get().countDown();
        return invocation.proceed();
    });
    final AtomicInteger count = new AtomicInteger();
    class TestSourceAdvice extends AbstractMessageSourceAdvice {

        @Override
        public boolean beforeReceive(MessageSource<?> target) {
            count.incrementAndGet();
            callOrder.add("b");
            latch.get().countDown();
            return true;
        }

        @Override
        public Message<?> afterReceive(Message<?> result, MessageSource<?> target) {
            callOrder.add("d");
            latch.get().countDown();
            return result;
        }
    }
    adviceChain.add(new TestSourceAdvice());
    adapter.setAdviceChain(adviceChain);
    adapter.afterPropertiesSet();
    adapter.start();
    assertTrue(latch.get().await(10, TimeUnit.SECONDS));
    // advice + advice + source + advice
    assertThat(callOrder, contains("a", "b", "c", "d"));
    adapter.stop();
    trigger.reset();
    latch.set(new CountDownLatch(4));
    adapter.start();
    assertTrue(latch.get().await(10, TimeUnit.SECONDS));
    adapter.stop();
    assertEquals(2, count.get());
    // Now test when the source is already a proxy.
    ProxyFactory pf = new ProxyFactory(source);
    pf.addAdvice((MethodInterceptor) Joinpoint::proceed);
    adapter.setSource((MessageSource<?>) pf.getProxy());
    trigger.reset();
    latch.set(new CountDownLatch(4));
    count.set(0);
    callOrder.clear();
    adapter.start();
    assertTrue(latch.get().await(10, TimeUnit.SECONDS));
    // advice + advice + source + advice
    assertThat(callOrder, contains("a", "b", "c", "d"));
    adapter.stop();
    trigger.reset();
    latch.set(new CountDownLatch(4));
    adapter.start();
    assertTrue(latch.get().await(10, TimeUnit.SECONDS));
    adapter.stop();
    assertEquals(2, count.get());
    Advisor[] advisors = ((Advised) adapter.getMessageSource()).getAdvisors();
    // make sure we didn't remove the original one
    assertEquals(2, advisors.length);
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) Date(java.util.Date) SimpleActiveIdleMessageSourceAdvice(org.springframework.integration.aop.SimpleActiveIdleMessageSourceAdvice) Autowired(org.springframework.beans.factory.annotation.Autowired) DynamicPeriodicTrigger(org.springframework.integration.util.DynamicPeriodicTrigger) Assert.assertThat(org.junit.Assert.assertThat) OnlyOnceTrigger(org.springframework.integration.test.util.OnlyOnceTrigger) SpringJUnit4ClassRunner(org.springframework.test.context.junit4.SpringJUnit4ClassRunner) NullChannel(org.springframework.integration.channel.NullChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Mockito.atLeast(org.mockito.Mockito.atLeast) TriggerContext(org.springframework.scheduling.TriggerContext) Trigger(org.springframework.scheduling.Trigger) CompoundTriggerAdvice(org.springframework.integration.aop.CompoundTriggerAdvice) EnableIntegration(org.springframework.integration.config.EnableIntegration) MessageChannel(org.springframework.messaging.MessageChannel) SimplePollSkipStrategy(org.springframework.integration.scheduling.SimplePollSkipStrategy) Configuration(org.springframework.context.annotation.Configuration) ServiceActivator(org.springframework.integration.annotation.ServiceActivator) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Log4j2LevelAdjuster(org.springframework.integration.test.rule.Log4j2LevelAdjuster) Matchers.contains(org.hamcrest.Matchers.contains) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) DirectChannel(org.springframework.integration.channel.DirectChannel) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractMessageSourceAdvice(org.springframework.integration.aop.AbstractMessageSourceAdvice) Advised(org.springframework.aop.framework.Advised) RunWith(org.junit.runner.RunWith) ExpressionControlBusFactoryBean(org.springframework.integration.config.ExpressionControlBusFactoryBean) Mockito.spy(org.mockito.Mockito.spy) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageSource(org.springframework.integration.core.MessageSource) ArrayList(java.util.ArrayList) Joinpoint(org.aopalliance.intercept.Joinpoint) Advice(org.aopalliance.aop.Advice) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Message(org.springframework.messaging.Message) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) LinkedList(java.util.LinkedList) Advisor(org.springframework.aop.Advisor) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) PollSkipAdvice(org.springframework.integration.scheduling.PollSkipAdvice) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) Rule(org.junit.Rule) BeanFactory(org.springframework.beans.factory.BeanFactory) ContextConfiguration(org.springframework.test.context.ContextConfiguration) ProxyFactory(org.springframework.aop.framework.ProxyFactory) Bean(org.springframework.context.annotation.Bean) CompoundTrigger(org.springframework.integration.util.CompoundTrigger) GenericMessage(org.springframework.messaging.support.GenericMessage) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) AbstractMessageSourceAdvice(org.springframework.integration.aop.AbstractMessageSourceAdvice) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) ProxyFactory(org.springframework.aop.framework.ProxyFactory) ArrayList(java.util.ArrayList) MessageSource(org.springframework.integration.core.MessageSource) Advisor(org.springframework.aop.Advisor) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) OnlyOnceTrigger(org.springframework.integration.test.util.OnlyOnceTrigger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Advised(org.springframework.aop.framework.Advised) SimpleActiveIdleMessageSourceAdvice(org.springframework.integration.aop.SimpleActiveIdleMessageSourceAdvice) CompoundTriggerAdvice(org.springframework.integration.aop.CompoundTriggerAdvice) AbstractMessageSourceAdvice(org.springframework.integration.aop.AbstractMessageSourceAdvice) Advice(org.aopalliance.aop.Advice) PollSkipAdvice(org.springframework.integration.scheduling.PollSkipAdvice) Test(org.junit.Test)

Aggregations

Trigger (org.springframework.scheduling.Trigger)17 Test (org.junit.Test)14 PeriodicTrigger (org.springframework.scheduling.support.PeriodicTrigger)13 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)10 CronTrigger (org.springframework.scheduling.support.CronTrigger)8 TriggerContext (org.springframework.scheduling.TriggerContext)7 Date (java.util.Date)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 SourcePollingChannelAdapter (org.springframework.integration.endpoint.SourcePollingChannelAdapter)5 OnlyOnceTrigger (org.springframework.integration.test.util.OnlyOnceTrigger)5 Expression (org.springframework.expression.Expression)4 CompoundTriggerAdvice (org.springframework.integration.aop.CompoundTriggerAdvice)4 PollerMetadata (org.springframework.integration.scheduling.PollerMetadata)4 CompoundTrigger (org.springframework.integration.util.CompoundTrigger)4 DynamicPeriodicTrigger (org.springframework.integration.util.DynamicPeriodicTrigger)4 ArrayList (java.util.ArrayList)3 Advice (org.aopalliance.aop.Advice)3 AbstractMessageSourceAdvice (org.springframework.integration.aop.AbstractMessageSourceAdvice)3 SimpleActiveIdleMessageSourceAdvice (org.springframework.integration.aop.SimpleActiveIdleMessageSourceAdvice)3 PollSkipAdvice (org.springframework.integration.scheduling.PollSkipAdvice)3