Search in sources :

Example 1 with CronTask

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

the class ScheduledAnnotationBeanPostProcessorTests method expressionWithCron.

@Test
public void expressionWithCron() {
    String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
    BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
    BeanDefinition targetDefinition = new RootBeanDefinition(ExpressionWithCronTestBean.class);
    context.registerBeanDefinition("postProcessor", processorDefinition);
    context.registerBeanDefinition("target", targetDefinition);
    Map<String, String> schedules = new HashMap<>();
    schedules.put("businessHours", businessHoursCronExpression);
    context.getBeanFactory().registerSingleton("schedules", schedules);
    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("x", targetMethod.getName());
    assertEquals(businessHoursCronExpression, task.getExpression());
}
Also used : HashMap(java.util.HashMap) CronTask(org.springframework.scheduling.config.CronTask) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable) ScheduledTaskRegistrar(org.springframework.scheduling.config.ScheduledTaskRegistrar) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) List(java.util.List) Test(org.junit.Test)

Example 2 with CronTask

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

the class ScheduledAnnotationBeanPostProcessorTests method propertyPlaceholderForMetaAnnotation.

@Test
public void propertyPlaceholderForMetaAnnotation() {
    String businessHoursCronExpression = "0 0 9-17 * * MON-FRI";
    BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
    BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class);
    Properties properties = new Properties();
    properties.setProperty("schedules.businessHours", businessHoursCronExpression);
    placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties);
    BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderMetaAnnotationTestBean.class);
    context.registerBeanDefinition("postProcessor", processorDefinition);
    context.registerBeanDefinition("placeholder", placeholderDefinition);
    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("y", targetMethod.getName());
    assertEquals(businessHoursCronExpression, task.getExpression());
}
Also used : CronTask(org.springframework.scheduling.config.CronTask) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Properties(java.util.Properties) ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable) ScheduledTaskRegistrar(org.springframework.scheduling.config.ScheduledTaskRegistrar) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) List(java.util.List) Test(org.junit.Test)

Example 3 with CronTask

use of org.springframework.scheduling.config.CronTask 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 4 with CronTask

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

the class ScheduledAnnotationBeanPostProcessorTests method metaAnnotationWithCronExpression.

@Test
public void metaAnnotationWithCronExpression() {
    BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class);
    BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationCronTestBean.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("generateReport", targetMethod.getName());
    assertEquals("0 0 * * * ?", task.getExpression());
}
Also used : ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable) ScheduledTaskRegistrar(org.springframework.scheduling.config.ScheduledTaskRegistrar) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) CronTask(org.springframework.scheduling.config.CronTask) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) List(java.util.List) Method(java.lang.reflect.Method) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Test(org.junit.Test)

Example 5 with CronTask

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

the class ScheduledAnnotationBeanPostProcessor method processScheduled.

protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
    try {
        Assert.isTrue(method.getParameterCount() == 0, "Only no-arg methods may be annotated with @Scheduled");
        Method invocableMethod = AopUtils.selectInvocableMethod(method, bean.getClass());
        Runnable runnable = new ScheduledMethodRunnable(bean, invocableMethod);
        boolean processedSchedule = false;
        String errorMessage = "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";
        Set<ScheduledTask> tasks = new LinkedHashSet<>(4);
        // Determine initial delay
        long initialDelay = scheduled.initialDelay();
        String initialDelayString = scheduled.initialDelayString();
        if (StringUtils.hasText(initialDelayString)) {
            Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
            if (this.embeddedValueResolver != null) {
                initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString);
            }
            try {
                initialDelay = Long.parseLong(initialDelayString);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into integer");
            }
        }
        // Check cron expression
        String cron = scheduled.cron();
        if (StringUtils.hasText(cron)) {
            Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
            processedSchedule = true;
            String zone = scheduled.zone();
            if (this.embeddedValueResolver != null) {
                cron = this.embeddedValueResolver.resolveStringValue(cron);
                zone = this.embeddedValueResolver.resolveStringValue(zone);
            }
            TimeZone timeZone;
            if (StringUtils.hasText(zone)) {
                timeZone = StringUtils.parseTimeZoneString(zone);
            } else {
                timeZone = TimeZone.getDefault();
            }
            tasks.add(this.registrar.scheduleCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone))));
        }
        // At this point we don't need to differentiate between initial delay set or not anymore
        if (initialDelay < 0) {
            initialDelay = 0;
        }
        // Check fixed delay
        long fixedDelay = scheduled.fixedDelay();
        if (fixedDelay >= 0) {
            Assert.isTrue(!processedSchedule, errorMessage);
            processedSchedule = true;
            tasks.add(this.registrar.scheduleFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay)));
        }
        String fixedDelayString = scheduled.fixedDelayString();
        if (StringUtils.hasText(fixedDelayString)) {
            Assert.isTrue(!processedSchedule, errorMessage);
            processedSchedule = true;
            if (this.embeddedValueResolver != null) {
                fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
            }
            try {
                fixedDelay = Long.parseLong(fixedDelayString);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into integer");
            }
            tasks.add(this.registrar.scheduleFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay)));
        }
        // Check fixed rate
        long fixedRate = scheduled.fixedRate();
        if (fixedRate >= 0) {
            Assert.isTrue(!processedSchedule, errorMessage);
            processedSchedule = true;
            tasks.add(this.registrar.scheduleFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay)));
        }
        String fixedRateString = scheduled.fixedRateString();
        if (StringUtils.hasText(fixedRateString)) {
            Assert.isTrue(!processedSchedule, errorMessage);
            processedSchedule = true;
            if (this.embeddedValueResolver != null) {
                fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
            }
            try {
                fixedRate = Long.parseLong(fixedRateString);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into integer");
            }
            tasks.add(this.registrar.scheduleFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay)));
        }
        // Check whether we had any attribute set
        Assert.isTrue(processedSchedule, errorMessage);
        // Finally register the scheduled tasks
        synchronized (this.scheduledTasks) {
            Set<ScheduledTask> registeredTasks = this.scheduledTasks.get(bean);
            if (registeredTasks == null) {
                registeredTasks = new LinkedHashSet<>(4);
                this.scheduledTasks.put(bean, registeredTasks);
            }
            registeredTasks.addAll(tasks);
        }
    } catch (IllegalArgumentException ex) {
        throw new IllegalStateException("Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage());
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) CronTrigger(org.springframework.scheduling.support.CronTrigger) CronTask(org.springframework.scheduling.config.CronTask) ScheduledTask(org.springframework.scheduling.config.ScheduledTask) Method(java.lang.reflect.Method) ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable) TimeZone(java.util.TimeZone) IntervalTask(org.springframework.scheduling.config.IntervalTask) ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable)

Aggregations

Method (java.lang.reflect.Method)8 CronTask (org.springframework.scheduling.config.CronTask)8 ScheduledMethodRunnable (org.springframework.scheduling.support.ScheduledMethodRunnable)8 List (java.util.List)7 Test (org.junit.Test)7 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)7 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)7 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)7 ScheduledTaskRegistrar (org.springframework.scheduling.config.ScheduledTaskRegistrar)7 Properties (java.util.Properties)2 CronTrigger (org.springframework.scheduling.support.CronTrigger)2 Calendar (java.util.Calendar)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 TimeZone (java.util.TimeZone)1 Trigger (org.springframework.scheduling.Trigger)1 TriggerContext (org.springframework.scheduling.TriggerContext)1 IntervalTask (org.springframework.scheduling.config.IntervalTask)1 ScheduledTask (org.springframework.scheduling.config.ScheduledTask)1