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

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

Introduction

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

Prototype

public CronTrigger(String expression) 

Source Link

Document

Build a CronTrigger from the pattern provided in the default time zone.

Usage

From source file:com.bleum.canton.jms.scheduler.AbstractJMSScheduler.java

/**
 * Auto start the scheduler after all properties set.
 *///w w w . j  a v  a 2s. c o  m
@PostConstruct
private void start() {
    // initialize Spring ThreadPoolTaskScheduler
    threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.initialize();

    // set properties
    setProperties();

    // Spring ThreadPoolTaskScheduler
    Date startDate = new Date(System.currentTimeMillis() + initialDelay);
    if (fixedDelay > 0) {
        threadPoolTaskScheduler.scheduleWithFixedDelay(this, startDate, fixedDelay);
    } else if (fixedRate > 0) {
        threadPoolTaskScheduler.scheduleAtFixedRate(this, startDate, fixedDelay);
    } else if (StringUtils.isNotBlank(cron)) {
        threadPoolTaskScheduler.schedule(this, new CronTrigger(cron));
    } else {
        threadPoolTaskScheduler.scheduleWithFixedDelay(this, startDate, JMSTaskConstant.DEFAULT_FIXED_DELAY);
    }
}

From source file:io.pivotal.strepsirrhini.chaosloris.destroyer.DestructionSchedulerTest.java

@Test
@SuppressWarnings("unchecked")
public void stop() {
    Schedule schedule = new Schedule("0 0 * * * *", "hourly");
    schedule.setId(-1L);//from   w w  w . j  av a2s .c  o m

    Destroyer destroyer = mock(Destroyer.class, RETURNS_SMART_NULLS);
    ScheduledFuture future = mock(ScheduledFuture.class, RETURNS_SMART_NULLS);
    when(this.destroyerFactory.create(schedule.getId())).thenReturn(destroyer);
    when(this.scheduleRepository.findAll()).thenReturn(Collections.singletonList(schedule));
    when(this.taskScheduler.schedule(destroyer, new CronTrigger(schedule.getExpression()))).thenReturn(future);

    this.destructionScheduler.start();
    this.destructionScheduler.stop();

    verify(future).cancel(false);
}

From source file:org.apache.archiva.indexer.merger.DefaultMergedRemoteIndexesScheduler.java

@Override
public void schedule(RepositoryGroup repositoryGroup, File directory) {
    if (StringUtils.isEmpty(repositoryGroup.getCronExpression())) {
        return;//from w  w w .java2 s  .  com
    }
    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);
}

From source file:org.apache.archiva.scheduler.indexing.DefaultDownloadRemoteIndexScheduler.java

@Override
public void scheduleDownloadRemote(String repositoryId, boolean now, boolean fullDownload)
        throws DownloadRemoteIndexException {
    try {//  www.  j  a v  a2  s . c om
        RemoteRepository remoteRepository = remoteRepositoryAdmin.getRemoteRepository(repositoryId);
        if (remoteRepository == null) {
            log.warn("ignore scheduleDownloadRemote for repo with id {} as not exists", repositoryId);
            return;
        }
        NetworkProxy networkProxy = null;
        if (StringUtils.isNotBlank(remoteRepository.getRemoteDownloadNetworkProxyId())) {
            networkProxy = networkProxyAdmin
                    .getNetworkProxy(remoteRepository.getRemoteDownloadNetworkProxyId());
            if (networkProxy == null) {
                log.warn(
                        "your remote repository is configured to download remote index trought a proxy we cannot find id:{}",
                        remoteRepository.getRemoteDownloadNetworkProxyId());
            }
        }

        DownloadRemoteIndexTaskRequest downloadRemoteIndexTaskRequest = new DownloadRemoteIndexTaskRequest()
                .setRemoteRepository(remoteRepository).setNetworkProxy(networkProxy)
                .setFullDownload(fullDownload).setWagonFactory(wagonFactory)
                .setRemoteRepositoryAdmin(remoteRepositoryAdmin).setIndexUpdater(indexUpdater)
                .setIndexPacker(this.indexPacker);

        if (now) {
            log.info("schedule download remote index for repository {}", remoteRepository.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 {}",
                    remoteRepository.getId(), remoteRepository.getCronExpression());
            try {
                CronTrigger cronTrigger = new CronTrigger(remoteRepository.getCronExpression());
                taskScheduler.schedule(new DownloadRemoteIndexTask(downloadRemoteIndexTaskRequest,
                        this.runningRemoteDownloadIds), cronTrigger);
            } catch (IllegalArgumentException e) {
                log.warn("Unable to schedule remote index download: {}", e.getLocalizedMessage());
            }

            if (remoteRepository.isDownloadRemoteIndexOnStartup()) {
                log.info(
                        "remote repository {} configured with downloadRemoteIndexOnStartup schedule now a download",
                        remoteRepository.getId());
                taskScheduler.schedule(new DownloadRemoteIndexTask(downloadRemoteIndexTaskRequest,
                        this.runningRemoteDownloadIds), new Date());
            }
        }

    } catch (RepositoryAdminException e) {
        log.error(e.getMessage(), e);
        throw new DownloadRemoteIndexException(e.getMessage(), e);
    }
}

From source file:org.apache.archiva.scheduler.indexing.maven.DefaultDownloadRemoteIndexScheduler.java

@Override
public void scheduleDownloadRemote(String repositoryId, boolean now, boolean fullDownload)
        throws DownloadRemoteIndexException {
    try {// w w  w.j a v  a 2 s  .  co  m
        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);
    }
}

From source file:org.craftercms.deployer.impl.TargetImpl.java

@Override
public void scheduleDeployment(TaskScheduler scheduler, String cronExpression) {
    scheduledDeploymentFuture = scheduler.schedule(new ScheduledDeploymentTask(),
            new CronTrigger(cronExpression));
}

From source file:org.jasig.ssp.service.impl.ScheduledTaskWrapperServiceImpl.java

protected Trigger tryExpressionAsCronTrigger(String configValue) throws BadTriggerConfigException {
    try {// ww  w.j  av  a  2s . c o  m
        return new CronTrigger(configValue);
    } catch (IllegalArgumentException e) {
        throw new BadTriggerConfigException(
                "Config [" + configValue + "] could not be used to initialize a CronTrigger", configValue, e);
    }
}

From source file:org.jumpmind.metl.core.runtime.AgentRuntime.java

private void deploy(final AgentDeployment deployment) {
    DeploymentStatus status = deployment.getDeploymentStatus();
    if (!status.equals(DeploymentStatus.DISABLED) && !status.equals(DeploymentStatus.REQUEST_DISABLE)
            && !status.equals(DeploymentStatus.REQUEST_REMOVE)) {
        try {// w w w.  j a  v  a 2  s.c  o m
            log.info("Deploying '{}' to '{}'", deployment.getFlow().toString(), agent.getName());

            deployResources(deployment.getFlow());

            if (scheduledFlows.get(deployment) == null) {
                scheduledFlows.put(deployment, Collections.synchronizedList(new ArrayList<FlowRuntime>()));
            }

            doComponentDeploymentEvent(deployment, (l, f, s, c) -> l.onDeploy(agent, deployment, f, s, c));

            if (deployment.asStartType() == StartType.ON_DEPLOY) {
                scheduleNow(deployment);
            } else if (deployment.asStartType() == StartType.SCHEDULED_CRON) {
                String cron = deployment.getStartExpression();
                log.info(
                        "Scheduling '{}' on '{}' with a cron expression of '{}'  The next run time should be at: {}",
                        new Object[] { deployment.getFlow().toString(), agent.getName(), cron,
                                new CronSequenceGenerator(cron).next(new Date()) });

                ScheduledFuture<?> future = this.flowExecutionScheduler.schedule(
                        new FlowRunner(deployment, UUID.randomUUID().toString()), new CronTrigger(cron));
                scheduledDeployments.put(deployment, future);
            }

            deployment.setStatus(DeploymentStatus.DEPLOYED.name());
            deployment.setMessage("");
            log.info("Flow '{}' has been deployed", deployment.getFlow().getName());
        } catch (Exception e) {
            log.warn("Failed to start '{}'", deployment.getFlow().getName(), e);
            deployment.setStatus(DeploymentStatus.ERROR.name());
            deployment.setMessage(ExceptionUtils.getRootCauseMessage(e));
        }
        configurationService.save(deployment);
    }
}

From source file:org.jumpmind.symmetric.job.AbstractJob.java

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;/*from   w w  w .j av a 2s .c  o  m*/
        } 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);
            }
        }
    }
}

From source file:org.openiam.idm.srvc.batch.service.BatchDataServiceImpl.java

@Override
public Response save(final BatchTask task) {
    final Response response = new Response(ResponseStatus.SUCCESS);
    try {//from w  w w. j a v  a2s .com
        if (task == null) {
            throw new BasicDataServiceException(ResponseCode.OBJECT_NOT_FOUND);
        }

        if (StringUtils.isBlank(task.getName())) {
            throw new BasicDataServiceException(ResponseCode.NO_NAME);
        }

        if (StringUtils.isBlank(task.getCronExpression()) && task.getRunOn() == null) {
            throw new BasicDataServiceException(ResponseCode.NO_EXEUCUTION_TIME);
        }

        if (StringUtils.isNotBlank(task.getCronExpression())) {
            try {
                new CronTrigger(task.getCronExpression());
            } catch (Throwable e) {
                throw new BasicDataServiceException(ResponseCode.INVALID_CRON_EXRPESSION);
            }
            task.setRunOn(null);
        }

        if (task.getRunOn() != null) {
            if (task.getRunOn().before(new Date())) {
                throw new BasicDataServiceException(ResponseCode.DATE_INVALID);
            }
            task.setCronExpression(null);
        }

        if (StringUtils.isBlank(task.getTaskUrl()) && (StringUtils.isBlank(task.getSpringBean())
                || StringUtils.isBlank(task.getSpringBeanMethod()))) {
            throw new BasicDataServiceException(ResponseCode.SPRING_BEAN_OR_SCRIPT_REQUIRED);
        }

        if (StringUtils.isNotBlank(task.getTaskUrl())) {
            if (!scriptRunner.scriptExists(task.getTaskUrl())) {
                throw new BasicDataServiceException(ResponseCode.FILE_DOES_NOT_EXIST);
            }
            task.setSpringBean(null);
            task.setSpringBeanMethod(null);
        } else {
            boolean validBeanDefinition = false;
            try {
                if (ctx.containsBean(task.getSpringBean())) {
                    final Object bean = ctx.getBean(task.getSpringBean());
                    final Method method = ReflectionUtils.getMethod(bean, task.getSpringBeanMethod());
                    if (method != null && method.getParameterTypes().length == 0) {
                        validBeanDefinition = true;
                        task.setTaskUrl(null);
                    }
                }
            } catch (Throwable beanE) {
                validBeanDefinition = false;
            }

            if (!validBeanDefinition) {
                throw new BasicDataServiceException(ResponseCode.INVALID_SPRING_BEAN);
            }
        }

        final BatchTaskEntity entity = converter.convertToEntity(task, true);
        batchService.save(entity);
        response.setResponseValue(entity.getId());
    } catch (BasicDataServiceException e) {
        response.setErrorCode(e.getCode());
        response.setStatus(ResponseStatus.FAILURE);
    } catch (Throwable e) {
        LOG.error("Can't save", e);
        response.setErrorText(e.getMessage());
        response.setStatus(ResponseStatus.FAILURE);
    }
    return response;
}