Search in sources :

Example 1 with CronTrigger

use of org.springframework.scheduling.support.CronTrigger 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 CronTrigger

use of org.springframework.scheduling.support.CronTrigger in project dhis2-core by dhis2.

the class SpringScheduler method scheduleTask.

@Override
public boolean scheduleTask(String key, Runnable task, String cronExpr) {
    if (key != null && !futures.containsKey(key)) {
        ScheduledFuture<?> future = taskScheduler.schedule(task, new CronTrigger(cronExpr));
        futures.put(key, future);
        log.info("Scheduled task with key: " + key + " and cron: " + cronExpr);
        return true;
    }
    return false;
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger)

Example 3 with CronTrigger

use of org.springframework.scheduling.support.CronTrigger in project hub-alert by blackducksoftware.

the class CommonConfig method scheduleJobExecution.

public void scheduleJobExecution(final String cron) {
    if (StringUtils.isNotBlank(cron)) {
        try {
            final CronTrigger cronTrigger = new CronTrigger(cron, TimeZone.getTimeZone("UTC"));
            if (future != null) {
                future.cancel(false);
            }
            logger.info("Scheduling " + this.getClass().getSimpleName() + " with cron : " + cron);
            future = taskScheduler.schedule(this, cronTrigger);
        } catch (final IllegalArgumentException e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        if (future != null) {
            logger.info("Un-Scheduling " + this.getClass().getSimpleName());
            future.cancel(false);
        }
    }
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger)

Example 4 with CronTrigger

use of org.springframework.scheduling.support.CronTrigger in project archiva by apache.

the class DefaultMergedRemoteIndexesScheduler method schedule.

@Override
public void schedule(RepositoryGroup repositoryGroup, Path directory) {
    if (StringUtils.isEmpty(repositoryGroup.getCronExpression())) {
        return;
    }
    CronTrigger cronTrigger = new CronTrigger(repositoryGroup.getCronExpression());
    List<String> repositories = repositoryGroup.getRepositories();
    IndexMergerRequest indexMergerRequest = new IndexMergerRequest(repositories, true, repositoryGroup.getId(), repositoryGroup.getMergedIndexPath(), repositoryGroup.getMergedIndexTtl()).mergedIndexDirectory(directory);
    MergedRemoteIndexesTaskRequest taskRequest = new MergedRemoteIndexesTaskRequest(indexMergerRequest, indexMerger);
    logger.info("schedule merge remote index for group {} with cron {}", repositoryGroup.getId(), repositoryGroup.getCronExpression());
    ScheduledFuture scheduledFuture = taskScheduler.schedule(new MergedRemoteIndexesTask(taskRequest), cronTrigger);
    scheduledFutureMap.put(repositoryGroup.getId(), scheduledFuture);
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 5 with CronTrigger

use of org.springframework.scheduling.support.CronTrigger 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)

Aggregations

CronTrigger (org.springframework.scheduling.support.CronTrigger)14 Date (java.util.Date)4 Trigger (org.springframework.scheduling.Trigger)2 CronTask (org.springframework.scheduling.config.CronTask)2 ScheduledMethodRunnable (org.springframework.scheduling.support.ScheduledMethodRunnable)2 SyncHandler (io.gravitee.gateway.services.sync.handler.SyncHandler)1 Method (java.lang.reflect.Method)1 Calendar (java.util.Calendar)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 TimeZone (java.util.TimeZone)1 ScheduledFuture (java.util.concurrent.ScheduledFuture)1 RepositoryAdminException (org.apache.archiva.admin.model.RepositoryAdminException)1 NetworkProxy (org.apache.archiva.admin.model.beans.NetworkProxy)1 RemoteIndexFeature (org.apache.archiva.repository.features.RemoteIndexFeature)1 CamelThreadPoolTaskScheduler (org.apache.camel.spring.util.CamelThreadPoolTaskScheduler)1 Lock (org.jumpmind.symmetric.model.Lock)1 Test (org.junit.Test)1 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)1 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)1