Search in sources :

Example 11 with CronTrigger

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

the class DefaultDownloadRemoteIndexScheduler method scheduleDownloadRemote.

@Override
public void scheduleDownloadRemote(String repositoryId, boolean now, boolean fullDownload) throws DownloadRemoteIndexException {
    try {
        org.apache.archiva.repository.RemoteRepository remoteRepo = repositoryRegistry.getRemoteRepository(repositoryId);
        if (remoteRepo == null) {
            log.warn("ignore scheduleDownloadRemote for repo with id {} as not exists", repositoryId);
            return;
        }
        if (!remoteRepo.supportsFeature(RemoteIndexFeature.class)) {
            log.warn("ignore scheduleDownloadRemote for repo with id {}. Does not support remote index.", repositoryId);
            return;
        }
        RemoteIndexFeature rif = remoteRepo.getFeature(RemoteIndexFeature.class).get();
        NetworkProxy networkProxy = null;
        if (StringUtils.isNotBlank(rif.getProxyId())) {
            networkProxy = networkProxyAdmin.getNetworkProxy(rif.getProxyId());
            if (networkProxy == null) {
                log.warn("your remote repository is configured to download remote index trought a proxy we cannot find id:{}", rif.getProxyId());
            }
        }
        DownloadRemoteIndexTaskRequest downloadRemoteIndexTaskRequest = // 
        new DownloadRemoteIndexTaskRequest().setRemoteRepository(// 
        remoteRepo).setNetworkProxy(// 
        networkProxy).setFullDownload(// 
        fullDownload).setWagonFactory(// 
        wagonFactory).setIndexUpdater(// 
        indexUpdater).setIndexPacker(this.indexPacker);
        if (now) {
            log.info("schedule download remote index for repository {}", remoteRepo.getId());
            // do it now
            taskScheduler.schedule(new DownloadRemoteIndexTask(downloadRemoteIndexTaskRequest, this.runningRemoteDownloadIds), new Date());
        } else {
            log.info("schedule download remote index for repository {} with cron expression {}", remoteRepo.getId(), remoteRepo.getSchedulingDefinition());
            try {
                CronTrigger cronTrigger = new CronTrigger(remoteRepo.getSchedulingDefinition());
                taskScheduler.schedule(new DownloadRemoteIndexTask(downloadRemoteIndexTaskRequest, this.runningRemoteDownloadIds), cronTrigger);
            } catch (IllegalArgumentException e) {
                log.warn("Unable to schedule remote index download: {}", e.getLocalizedMessage());
            }
            if (rif.isDownloadRemoteIndexOnStartup()) {
                log.info("remote repository {} configured with downloadRemoteIndexOnStartup schedule now a download", remoteRepo.getId());
                taskScheduler.schedule(new DownloadRemoteIndexTask(downloadRemoteIndexTaskRequest, this.runningRemoteDownloadIds), new Date());
            }
        }
    } catch (RepositoryAdminException e) {
        log.error(e.getMessage(), e);
        throw new DownloadRemoteIndexException(e.getMessage(), e);
    }
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger) RemoteIndexFeature(org.apache.archiva.repository.features.RemoteIndexFeature) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) NetworkProxy(org.apache.archiva.admin.model.beans.NetworkProxy) Date(java.util.Date)

Example 12 with CronTrigger

use of org.springframework.scheduling.support.CronTrigger in project gravitee-gateway by gravitee-io.

the class ScheduledSyncService method doStart.

@Override
protected void doStart() throws Exception {
    if (!localRegistryEnabled) {
        if (enabled) {
            super.doStart();
            logger.info("Sync service has been initialized with cron [{}]", cronTrigger);
            // Sync must start only when doStart() is invoked, that's the reason why we are not
            // using @Scheduled annotation on doSync() method.
            scheduler.schedule(this, new CronTrigger(cronTrigger));
            logger.info("Associate a new HTTP handler on {}", PATH);
            // Create and associate handler
            SyncHandler syncHandler = new SyncHandler();
            applicationContext.getAutowireCapableBeanFactory().autowireBean(syncHandler);
            router.get(PATH).produces(MediaType.APPLICATION_JSON).handler(syncHandler);
        } else {
            logger.warn("Sync service has been disabled");
        }
    } else {
        logger.warn("Sync service is disabled because local registry mode is enabled");
    }
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger) SyncHandler(io.gravitee.gateway.services.sync.handler.SyncHandler)

Example 13 with CronTrigger

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

the class ScheduledAnnotationBeanPostProcessor method processScheduled.

/**
 * Process the given {@code @Scheduled} method declaration on the given bean.
 * @param scheduled the {@code @Scheduled} annotation
 * @param method the method that the annotation has been declared on
 * @param bean the target bean instance
 * @see #createRunnable(Object, Method)
 */
protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
    try {
        Runnable runnable = createRunnable(bean, method);
        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 = convertToMillis(scheduled.initialDelay(), scheduled.timeUnit());
        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);
            }
            if (StringUtils.hasLength(initialDelayString)) {
                try {
                    initialDelay = convertToMillis(initialDelayString, scheduled.timeUnit());
                } catch (RuntimeException ex) {
                    throw new IllegalArgumentException("Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into long");
                }
            }
        }
        // Check cron expression
        String cron = scheduled.cron();
        if (StringUtils.hasText(cron)) {
            String zone = scheduled.zone();
            if (this.embeddedValueResolver != null) {
                cron = this.embeddedValueResolver.resolveStringValue(cron);
                zone = this.embeddedValueResolver.resolveStringValue(zone);
            }
            if (StringUtils.hasLength(cron)) {
                Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
                processedSchedule = true;
                if (!Scheduled.CRON_DISABLED.equals(cron)) {
                    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 = convertToMillis(scheduled.fixedDelay(), scheduled.timeUnit());
        if (fixedDelay >= 0) {
            Assert.isTrue(!processedSchedule, errorMessage);
            processedSchedule = true;
            tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
        }
        String fixedDelayString = scheduled.fixedDelayString();
        if (StringUtils.hasText(fixedDelayString)) {
            if (this.embeddedValueResolver != null) {
                fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
            }
            if (StringUtils.hasLength(fixedDelayString)) {
                Assert.isTrue(!processedSchedule, errorMessage);
                processedSchedule = true;
                try {
                    fixedDelay = convertToMillis(fixedDelayString, scheduled.timeUnit());
                } catch (RuntimeException ex) {
                    throw new IllegalArgumentException("Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into long");
                }
                tasks.add(this.registrar.scheduleFixedDelayTask(new FixedDelayTask(runnable, fixedDelay, initialDelay)));
            }
        }
        // Check fixed rate
        long fixedRate = convertToMillis(scheduled.fixedRate(), scheduled.timeUnit());
        if (fixedRate >= 0) {
            Assert.isTrue(!processedSchedule, errorMessage);
            processedSchedule = true;
            tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay)));
        }
        String fixedRateString = scheduled.fixedRateString();
        if (StringUtils.hasText(fixedRateString)) {
            if (this.embeddedValueResolver != null) {
                fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
            }
            if (StringUtils.hasLength(fixedRateString)) {
                Assert.isTrue(!processedSchedule, errorMessage);
                processedSchedule = true;
                try {
                    fixedRate = convertToMillis(fixedRateString, scheduled.timeUnit());
                } catch (RuntimeException ex) {
                    throw new IllegalArgumentException("Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into long");
                }
                tasks.add(this.registrar.scheduleFixedRateTask(new FixedRateTask(runnable, fixedRate, initialDelay)));
            }
        }
        // Check whether we had any attribute set
        Assert.isTrue(processedSchedule, errorMessage);
        // Finally register the scheduled tasks
        synchronized (this.scheduledTasks) {
            Set<ScheduledTask> regTasks = this.scheduledTasks.computeIfAbsent(bean, key -> new LinkedHashSet<>(4));
            regTasks.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) FixedRateTask(org.springframework.scheduling.config.FixedRateTask) CronTask(org.springframework.scheduling.config.CronTask) ScheduledTask(org.springframework.scheduling.config.ScheduledTask) TimeZone(java.util.TimeZone) ScheduledMethodRunnable(org.springframework.scheduling.support.ScheduledMethodRunnable) FixedDelayTask(org.springframework.scheduling.config.FixedDelayTask)

Example 14 with CronTrigger

use of org.springframework.scheduling.support.CronTrigger in project symmetric-ds by JumpMind.

the class AbstractJob method start.

public void start() {
    if (this.scheduledJob == null && engine != null && !engine.getClusterService().isInfiniteLocked(getClusterLockName())) {
        String cronExpression = engine.getParameterService().getString(jobName + ".cron", null);
        int timeBetweenRunsInMs = engine.getParameterService().getInt(jobName + ".period.time.ms", -1);
        if (!StringUtils.isBlank(cronExpression)) {
            log.info("Starting {} with cron expression: {}", jobName, cronExpression);
            this.scheduledJob = taskScheduler.schedule(this, new CronTrigger(cronExpression));
            started = true;
        } else {
            int startDelay = randomTimeSlot.getRandomValueSeededByExternalId();
            long currentTimeMillis = System.currentTimeMillis();
            long lastRunTime = currentTimeMillis - timeBetweenRunsInMs;
            Lock lock = engine.getClusterService().findLocks().get(getClusterLockName());
            if (lock != null && lock.getLastLockTime() != null) {
                long newRunTime = lock.getLastLockTime().getTime();
                if (lastRunTime < newRunTime) {
                    lastRunTime = newRunTime;
                }
            }
            Date firstRun = new Date(lastRunTime + timeBetweenRunsInMs + startDelay);
            log.info("Starting {} on periodic schedule: every {}ms with the first run at {}", new Object[] { jobName, timeBetweenRunsInMs, firstRun });
            if (timeBetweenRunsInMs > 0) {
                this.scheduledJob = taskScheduler.scheduleWithFixedDelay(this, firstRun, timeBetweenRunsInMs);
                started = true;
            } else {
                log.error("Failed to schedule this job, {}", jobName);
            }
        }
    }
}
Also used : CronTrigger(org.springframework.scheduling.support.CronTrigger) Date(java.util.Date) Lock(org.jumpmind.symmetric.model.Lock)

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