org.springframework.batch.core.Job

Here are the examples of the java api org.springframework.batch.core.Job taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

54 Examples 7

19 Source : JobLauncherCommandLineRunnerTests.java
with Apache License 2.0
from yuanmabiji

/**
 * Tests for {@link JobLauncherCommandLineRunner}.
 *
 * @author Dave Syer
 * @author Jean-Pierre Bergamin
 * @author Mahmoud Ben Hreplacedine
 */
public clreplaced JobLauncherCommandLineRunnerTests {

    private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    private JobLauncherCommandLineRunner runner;

    private JobExplorer jobExplorer;

    private JobBuilderFactory jobs;

    private StepBuilderFactory steps;

    private Job job;

    private Step step;

    @Before
    public void init() {
        this.context.register(BatchConfiguration.clreplaced);
        this.context.refresh();
        JobRepository jobRepository = this.context.getBean(JobRepository.clreplaced);
        JobLauncher jobLauncher = this.context.getBean(JobLauncher.clreplaced);
        this.jobs = new JobBuilderFactory(jobRepository);
        PlatformTransactionManager transactionManager = this.context.getBean(PlatformTransactionManager.clreplaced);
        this.steps = new StepBuilderFactory(jobRepository, transactionManager);
        Tasklet tasklet = (contribution, chunkContext) -> null;
        this.step = this.steps.get("step").tasklet(tasklet).build();
        this.job = this.jobs.get("job").start(this.step).build();
        this.jobExplorer = this.context.getBean(JobExplorer.clreplaced);
        this.runner = new JobLauncherCommandLineRunner(jobLauncher, this.jobExplorer, jobRepository);
        this.context.getBean(BatchConfiguration.clreplaced).clear();
    }

    @After
    public void closeContext() {
        this.context.close();
    }

    @Test
    public void basicExecution() throws Exception {
        this.runner.execute(this.job, new JobParameters());
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
        this.runner.execute(this.job, new JobParametersBuilder().addLong("id", 1L).toJobParameters());
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(2);
    }

    @Test
    public void incrementExistingExecution() throws Exception {
        this.job = this.jobs.get("job").start(this.step).incrementer(new RunIdIncrementer()).build();
        this.runner.execute(this.job, new JobParameters());
        this.runner.execute(this.job, new JobParameters());
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(2);
    }

    @Test
    public void retryFailedExecution() throws Exception {
        this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()).incrementer(new RunIdIncrementer()).build();
        this.runner.execute(this.job, new JobParameters());
        this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
    }

    @Test
    public void runDifferentInstances() throws Exception {
        this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()).build();
        // start a job instance
        JobParameters jobParameters = new JobParametersBuilder().addString("name", "foo").toJobParameters();
        this.runner.execute(this.job, jobParameters);
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
        // start a different job instance
        JobParameters otherJobParameters = new JobParametersBuilder().addString("name", "bar").toJobParameters();
        this.runner.execute(this.job, otherJobParameters);
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(2);
    }

    @Test
    public void retryFailedExecutionOnNonRestartableJob() throws Exception {
        this.job = this.jobs.get("job").preventRestart().start(this.steps.get("step").tasklet(throwingTasklet()).build()).incrementer(new RunIdIncrementer()).build();
        this.runner.execute(this.job, new JobParameters());
        this.runner.execute(this.job, new JobParameters());
        // A failed job that is not restartable does not re-use the job params of
        // the last execution, but creates a new job instance when running it again.
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(2);
        replacedertThatExceptionOfType(JobRestartException.clreplaced).isThrownBy(() -> {
            // try to re-run a failed execution
            this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
            fail("expected JobRestartException");
        }).withMessageContaining("JobInstance already exists and is not restartable");
    }

    @Test
    public void retryFailedExecutionWithNonIdentifyingParameters() throws Exception {
        this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()).incrementer(new RunIdIncrementer()).build();
        JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false).toJobParameters();
        this.runner.execute(this.job, jobParameters);
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
        // try to re-run a failed execution with non identifying parameters
        this.runner.execute(this.job, new JobParametersBuilder(jobParameters).addLong("run.id", 1L).toJobParameters());
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
    }

    @Test
    public void retryFailedExecutionWithDifferentNonIdentifyingParametersFromPreviousExecution() throws Exception {
        this.job = this.jobs.get("job").start(this.steps.get("step").tasklet(throwingTasklet()).build()).incrementer(new RunIdIncrementer()).build();
        JobParameters jobParameters = new JobParametersBuilder().addLong("id", 1L, false).addLong("foo", 2L, false).toJobParameters();
        this.runner.execute(this.job, jobParameters);
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
        // try to re-run a failed execution with non identifying parameters
        this.runner.execute(this.job, new JobParametersBuilder().addLong("run.id", 1L).addLong("id", 2L, false).addLong("foo", 3L, false).toJobParameters());
        replacedertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hreplacedize(1);
        JobInstance jobInstance = this.jobExplorer.getJobInstance(0L);
        replacedertThat(this.jobExplorer.getJobExecutions(jobInstance)).hreplacedize(2);
        // first execution
        JobExecution firstJobExecution = this.jobExplorer.getJobExecution(0L);
        JobParameters parameters = firstJobExecution.getJobParameters();
        replacedertThat(parameters.getLong("run.id")).isEqualTo(1L);
        replacedertThat(parameters.getLong("id")).isEqualTo(1L);
        replacedertThat(parameters.getLong("foo")).isEqualTo(2L);
        // second execution
        JobExecution secondJobExecution = this.jobExplorer.getJobExecution(1L);
        parameters = secondJobExecution.getJobParameters();
        // identifying parameters should be the same as previous execution
        replacedertThat(parameters.getLong("run.id")).isEqualTo(1L);
        // non-identifying parameters should be the newly specified ones
        replacedertThat(parameters.getLong("id")).isEqualTo(2L);
        replacedertThat(parameters.getLong("foo")).isEqualTo(3L);
    }

    private Tasklet throwingTasklet() {
        return (contribution, chunkContext) -> {
            throw new RuntimeException("Planned");
        };
    }

    @Configuration
    @EnableBatchProcessing
    protected static clreplaced BatchConfiguration implements BatchConfigurer {

        private ResourcelessTransactionManager transactionManager = new ResourcelessTransactionManager();

        private JobRepository jobRepository;

        private MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean(this.transactionManager);

        public BatchConfiguration() throws Exception {
            this.jobRepository = this.jobRepositoryFactory.getObject();
        }

        public void clear() {
            this.jobRepositoryFactory.clear();
        }

        @Override
        public JobRepository getJobRepository() {
            return this.jobRepository;
        }

        @Override
        public PlatformTransactionManager getTransactionManager() {
            return this.transactionManager;
        }

        @Override
        public JobLauncher getJobLauncher() {
            SimpleJobLauncher launcher = new SimpleJobLauncher();
            launcher.setJobRepository(this.jobRepository);
            launcher.setTaskExecutor(new SyncTaskExecutor());
            return launcher;
        }

        @Override
        public JobExplorer getJobExplorer() throws Exception {
            return new MapJobExplorerFactoryBean(this.jobRepositoryFactory).getObject();
        }
    }
}

19 Source : RepositoryJobLauncherController.java
with Apache License 2.0
from ypmc

/**
 * @author clyde lou
 */
@RestController
@Slf4j
@RequestMapping("/repos")
public clreplaced RepositoryJobLauncherController {

    @Autowired
    private JobLaunchService jobLaunchService;

    @Autowired
    private Job jobWithRepositoryStepWithParams;

    @Autowired
    private Job jobWithRepositoryStep;

    @GetMapping("/param")
    public JobResult launchJobWithRepositoryStepWithParams() {
        return jobLaunchService.launchJob(jobWithRepositoryStepWithParams);
    }

    @GetMapping
    public JobResult launchJobWithRepositoryStep() {
        return jobLaunchService.launchJob(jobWithRepositoryStep);
    }
}

19 Source : JpaPagingJobLauncherController.java
with Apache License 2.0
from ypmc

/**
 * @author clyde lou
 */
@RestController
@Slf4j
@RequestMapping("/jpa")
public clreplaced JpaPagingJobLauncherController {

    @Autowired
    private JobLaunchService jobLaunchService;

    @Autowired
    private Job jobInJpaPagingWithJdbcBatchItemWriter;

    @Autowired
    private Job jobInJpaPagingWithRepositoryItemWriter;

    @GetMapping("/jdbc")
    public JobResult launchJobInJpaPagingWithJdbcBatchItemWriter() {
        return jobLaunchService.launchJob(jobInJpaPagingWithJdbcBatchItemWriter);
    }

    @GetMapping("/repos")
    public JobResult launchJobInJpaPagingWithRepositoryItemWriter() {
        return jobLaunchService.launchJob(jobInJpaPagingWithRepositoryItemWriter);
    }
}

19 Source : FlatFileJobLauncherController.java
with Apache License 2.0
from ypmc

/**
 * @author clyde lou
 */
@RestController
@Slf4j
@RequestMapping("/flat")
public clreplaced FlatFileJobLauncherController {

    @Autowired
    private JobLaunchService jobLaunchService;

    @Autowired
    private Job jobUseFlatFileWithRepositoryItemWriter;

    @Autowired
    private Job jobUseFlatFileWithJdbcBatchItemWriter;

    @GetMapping("/repos")
    public JobResult launchJobUseFlatFileWithRepositoryItemWriter() {
        return jobLaunchService.launchJob(jobUseFlatFileWithRepositoryItemWriter);
    }

    @GetMapping("/jdbc")
    public JobResult launchJobUseFlatFileWithJdbcBatchItemWriter() {
        return jobLaunchService.launchJob(jobUseFlatFileWithJdbcBatchItemWriter);
    }
}

19 Source : BatchJobController.java
with MIT License
from tensult

@RestController
public clreplaced BatchJobController {

    @Autowired
    JobRepository jobRepository;

    @Bean
    public JobLauncher aysncJobLauncher() {
        final SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(jobRepository);
        final SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();
        simpleAsyncTaskExecutor.setConcurrencyLimit(1);
        jobLauncher.setTaskExecutor(simpleAsyncTaskExecutor);
        return jobLauncher;
    }

    @Autowired
    Job job;

    @RequestMapping(value = "/start", params = { "s3Folder", "numRecordsInBatch" }, method = RequestMethod.GET)
    public String handle(@RequestParam("s3Folder") String s3Folder, @RequestParam("numRecordsInBatch") String numRecordsInBatch) throws Exception {
        Map<String, JobParameter> jobParams = new LinkedHashMap<String, JobParameter>();
        jobParams.put("s3Folder", new JobParameter(s3Folder));
        jobParams.put("numRecordsInBatch", new JobParameter(numRecordsInBatch));
        aysncJobLauncher().run(job, new JobParameters(jobParams));
        System.out.println("Job started");
        return "started";
    }

    @RequestMapping(value = "/status", params = { "s3Folder", "numRecordsInBatch" }, method = RequestMethod.GET)
    public String getJobStatus(@RequestParam("s3Folder") String s3Folder, @RequestParam("numRecordsInBatch") String numRecordsInBatch) throws Exception {
        Map<String, JobParameter> jobParams = new LinkedHashMap<String, JobParameter>();
        jobParams.put("s3Folder", new JobParameter(s3Folder));
        jobParams.put("numRecordsInBatch", new JobParameter(numRecordsInBatch));
        JobExecution jobExecution = jobRepository.getLastJobExecution(job.getName(), new JobParameters(jobParams));
        return jobExecution != null ? jobExecution.getExitStatus().getExitCode() : ExitStatus.UNKNOWN.getExitCode();
    }

    @RequestMapping(value = "/api", method = RequestMethod.POST)
    public APIResponse postAPI() throws Exception {
        Random random = new Random();
        APIResponse response = new APIResponse();
        if (random.nextInt(10) > 7) {
            response.setStatus("failed");
            response.setMessage("Error" + random.nextInt(10));
        } else {
            response.setStatus("success");
            response.setMessage("ok");
        }
        return response;
    }
}

19 Source : ComposedTaskRunnerConfigurationJobIncrementerTests.java
with Apache License 2.0
from spring-cloud-task-app-starters

/**
 * @author Glenn Renfro
 */
@RunWith(SpringRunner.clreplaced)
@ContextConfiguration(clreplacedes = { EmbeddedDataSourceConfiguration.clreplaced, DataFlowTestConfiguration.clreplaced, StepBeanDefinitionRegistrar.clreplaced, ComposedTaskRunnerConfiguration.clreplaced, StepBeanDefinitionRegistrar.clreplaced })
@EnableAutoConfiguration(exclude = { CommonSecurityAutoConfiguration.clreplaced })
@TestPropertySource(properties = { "graph=AAA && BBB && CCC", "max-wait-time=1000", "increment-instance-enabled=true" })
public clreplaced ComposedTaskRunnerConfigurationJobIncrementerTests {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    protected Job job;

    @Test
    @DirtiesContext
    public void testComposedConfigurationWithJobIncrementer() throws Exception {
        this.jobRepository.createJobExecution("ComposedTest", new JobParameters());
        replacedert.notNull(job.getJobParametersIncrementer(), "JobParametersIncrementer must not be null.");
    }
}

19 Source : SpringBatchFlowRunner.java
with Apache License 2.0
from spring-cloud

@Override
public ExecutionResult runPostReleaseTrainTasks(Options options, ReleaserProperties properties, String taskName, TasksToRun tasksToRun) {
    ProjectsToRun projectsToRun = postReleaseTrainProjects(new OptionsAndProperties(properties, options));
    Flow flow = postReleaseFlow(tasksToRun, properties, projectsToRun);
    String name = taskName + "_" + System.currentTimeMillis();
    if (flow == null) {
        log.info("No release train post release tasks to run, will do nothing");
        return ExecutionResult.success();
    }
    Job job = this.jobBuilderFactory.get(name).start(flow).build().build();
    return runJob(job);
}

19 Source : SpringBatchFlowRunner.java
with Apache License 2.0
from spring-cloud

private ExecutionResult runJob(Job job) {
    try {
        JobExecution execution = this.jobLauncher.run(job, new JobParameters());
        if (!ExitStatus.COMPLETED.equals(execution.getExitStatus())) {
            return ExecutionResult.failure(new IllegalStateException("Job failed to get executed successfully. Failed with exit code [" + execution.getExitStatus().getExitCode() + "] and description [" + execution.getExitStatus().getExitDescription() + "]"));
        }
        List<Exception> thrownExceptions = exceptionsThrownBySteps(execution);
        return new ExecutionResult(thrownExceptions);
    } catch (JobExecutionException | UnexpectedJobExecutionException ex) {
        return ExecutionResult.failure(ex);
    }
}

19 Source : JobResource.java
with GNU General Public License v3.0
from michaelhoffmantech

/**
 * REST controller for getting the audit events.
 */
@RestController
@RequestMapping("/job")
public clreplaced JobResource {

    private final JobLauncher jobLauncher;

    private final Job job;

    public JobResource(JobLauncher jobLauncher, Job job) {
        this.jobLauncher = jobLauncher;
        this.job = job;
    }

    /**
     * POST /job/:fileName : post to execute a job using the file name given
     *
     * @param fileName
     *            the fileName of the job file to run
     * @return the ResponseEnreplacedy with status 200 (OK) or status 500 (Job Failure)
     */
    @GetMapping("/{fileName:.+}")
    public ResponseEnreplacedy<String> runJob(@PathVariable String fileName) {
        Map<String, JobParameter> parameterMap = new HashMap<>();
        parameterMap.put(Constants.JOB_PARAM_FILE_NAME, new JobParameter(fileName));
        try {
            jobLauncher.run(job, new JobParameters(parameterMap));
        } catch (Exception e) {
            return new ResponseEnreplacedy<String>("Failure: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEnreplacedy<String>("Success", HttpStatus.OK);
    }
}

19 Source : JobRunnerServiceImpl.java
with MIT License
from jonathanlermitage

@Service
public clreplaced JobRunnerServiceImpl implements InitializingBean, JobRunnerService {

    public JobRunnerServiceImpl(JobLauncher launcher, @Qualifier(UserSnapshotJobConfig.JOB_NAME) Job userSnapshotJob) {
        this.launcher = launcher;
        this.userSnapshotJob = userSnapshotJob;
    }

    private final JobLauncher launcher;

    private final Job userSnapshotJob;

    private Map<String, Job> jobs;

    @Override
    public void afterPropertiesSet() {
        this.jobs = Collections.singletonMap(UserSnapshotJobConfig.JOB_NAME, userSnapshotJob);
    }

    @Override
    public ExitStatus run(String job) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        if (jobs.containsKey(job)) {
            return launcher.run(jobs.get(job), todayDateJobParameters()).getExitStatus();
        }
        throw new TaskNotFoundException();
    }

    private JobParameters todayDateJobParameters() {
        return new JobParametersBuilder().addDate("START_DATE", Tools.nowAsDate()).toJobParameters();
    }
}

19 Source : BatchBean.java
with The Unlicense
from diegopacheco

@Controller
public clreplaced BatchBean {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;

    public String executar() {
        System.out.println("Executando Job do Spring Batch");
        try {
            System.out.println("Inicio da execu��o ");
            System.out.println("Job: " + job.getName());
            jobLauncher.run(job, new JobParameters());
            System.out.println("Fim da execu��o ");
        } catch (Exception e) {
            System.out.println("ERRO");
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return "";
    }
}

19 Source : SingleJobLauncher.java
with Apache License 2.0
from CogStack

/**
 * @author King's College London, Richard Jackson <[email protected]>
 */
@Service
@Import(JobConfiguration.clreplaced)
@ComponentScan({ "uk.ac.kcl.utils" })
public clreplaced SingleJobLauncher {

    @Autowired
    Environment env;

    @Autowired(required = false)
    Job job;

    @Autowired(required = false)
    BatchJobUtils batchJobUtils;

    @Autowired
    JobRepository jobRepository;

    @Autowired
    JobExplorer jobExplorer;

    @Autowired
    JobOperator jobOperator;

    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(SingleJobLauncher.clreplaced);

    public void launchJob() {
        JobExecution lastJobExecution = getLastJobExecution();
        try {
            if (lastJobExecution != null) {
                BatchStatus lastJobStatus = lastJobExecution.getStatus();
                switch(lastJobStatus) {
                    case COMPLETED:
                        LOG.info("Last job execution was successful");
                        startNextInstance();
                        break;
                    case STARTED:
                    case STARTING:
                    case STOPPING:
                        LOG.info("Job is already running. Repository in unknown state." + " Attempting to repair and restart from last successful job");
                        abandonAllJobsStartedAfterLastSuccessfulJob();
                        startNextInstance();
                        break;
                    case FAILED:
                        LOG.info("Last job failed. Attempting restart");
                        startNextInstance();
                        break;
                    case ABANDONED:
                        LOG.info("Last job was abandoned. Attempting start from last successful job");
                        abandonAllJobsStartedAfterLastSuccessfulJob();
                        startNextInstance();
                        break;
                    case STOPPED:
                        LOG.info("Last job was stopped. Attempting restart");
                        startNextInstance();
                        break;
                    case UNKNOWN:
                        LOG.info("Last job has unknown status. Marking as abandoned and attempting restart from last successful job");
                        abandonAllJobsStartedAfterLastSuccessfulJob();
                        startNextInstance();
                        break;
                    default:
                        LOG.error("Should be unreachable");
                        break;
                }
            } else {
                LOG.info("No previous completed jobs found");
                startNextInstance();
            }
        } catch (JobInstanceAlreadyCompleteException | JobExecutionAlreadyRunningException | JobParametersInvalidException e) {
            LOG.error("Cannot start job", e);
        } catch (JobRestartException e) {
            LOG.error("Cannot restart job. Attempting start from last successful job", e);
            try {
                jobOperator.abandon(lastJobExecution.getId());
                startNextInstance();
            } catch (NoSuchJobExecutionException | JobExecutionAlreadyRunningException | NoSuchJobException | JobInstanceAlreadyCompleteException | JobRestartException | JobParametersNotFoundException | JobParametersInvalidException e1) {
                throw new RuntimeException("Cannot start next instance", e1);
            }
        } catch (Exception e) {
            LOG.error("Cannot start job", e);
        }
    }

    private void startNextInstance() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException, JobParametersNotFoundException, NoSuchJobException {
        jobOperator.startNextInstance(job.getName());
    }

    private void abandonAllJobsStartedAfterLastSuccessfulJob() {
        List<Long> idsToAbandon = batchJobUtils.getExecutionIdsOfJobsToAbandon();
        for (Long id : idsToAbandon) {
            try {
                try {
                    jobOperator.stop(id);
                } catch (JobExecutionNotRunningException e) {
                    LOG.info("Cannot stop job execution ID " + id + " as it is already stopped. Attempting to mark as abandoned");
                }
                try {
                    jobOperator.abandon(id);
                } catch (JobExecutionAlreadyRunningException e) {
                    throw new RuntimeException("Cannot abandon job execution ID " + id + " as it appears to be running. " + "JobRepository may require inspection", e);
                }
            } catch (NoSuchJobExecutionException e) {
                throw new RuntimeException("Cannot mark job execution ID " + id + " as abandoned as it doesn't exist." + " JobRepository may require inspection)", e);
            }
        }
    }

    private JobExecution getLastJobExecution() {
        JobExecution lastJobExecution = null;
        try {
            lastJobExecution = batchJobUtils.getLastSuccessfulJobExecution();
        } catch (NullPointerException e) {
            LOG.info("No previous successful jobs found");
        }
        if (lastJobExecution == null) {
            try {
                lastJobExecution = batchJobUtils.getLastJobExecution();
            } catch (NullPointerException e) {
                LOG.info("No previous jobs found");
            }
        }
        return lastJobExecution;
    }
}

19 Source : AdHocScheduler.java
with Apache License 2.0
from chrisgleissner

/**
 * Schedules a Spring Batch job via a Quartz cron expression. Also registers the
 * job with the specified jobName, rather than the job param's name
 */
public synchronized Job schedule(String jobName, Job job, String cronExpression) {
    log.debug("Scheduling job {} with CRON expression {}", jobName, cronExpression);
    try {
        jobBuilder.registerJob(job);
        JobDetail jobDetail = this.jobDetailFor(jobName);
        Trigger trigger = TriggerUtil.triggerFor(cronExpression, jobName);
        scheduler.unscheduleJob(trigger.getKey());
        scheduler.scheduleJob(jobDetail, trigger);
        log.info("Scheduled job {} with CRON expression {}", jobName, cronExpression);
    } catch (Exception e) {
        throw new RuntimeException(format("Can't schedule job %s with cronExpression %s", jobName, cronExpression), e);
    }
    return job;
}

19 Source : AdHocScheduler.java
with Apache License 2.0
from chrisgleissner

/**
 * Schedules a Spring Batch job via a Quartz cron expression. Uses the job name
 * of the provided job.
 */
public synchronized Job schedule(Job job, String cronExpression) {
    return this.schedule(job.getName(), job, cronExpression);
}

19 Source : JobBuilder.java
with Apache License 2.0
from chrisgleissner

public Job registerJob(Job job) {
    return registerJob(jobRegistry, job);
}

19 Source : AdHocStarter.java
with Apache License 2.0
from chrisgleissner

public JobExecution start(Job job) {
    return this.start(job, true, null);
}

19 Source : AdHocStarter.java
with Apache License 2.0
from chrisgleissner

public JobExecution start(Job job, Boolean async, Map<String, Object> properties) {
    Job existingJob = null;
    try {
        existingJob = jobRegistry.getJob(job.getName());
    } catch (NoSuchJobException e) {
        log.info("Registering new job: " + job.getName());
    }
    JobConfig jobConfig = JobConfig.builder().asynchronous(async).properties(properties == null ? new HashMap<>() : properties).name(job.getName()).build();
    JobBuilder.registerJob(jobRegistry, existingJob == null ? job : existingJob);
    return this.start(jobConfig);
}

19 Source : PersonJobTest.java
with Apache License 2.0
from chrisgleissner

@Test
public void canStartJob() throws NoSuchJobException {
    Job job = jobRegistry.getJob(PersonJobConfig.JOB_NAME);
    replacedertThat(job).isNotNull();
    cacheItemWriter.clear();
    startJob(Optional.empty(), Optional.empty());
    replacedertThat(cacheItemWriter.gereplacedems()).hreplacedize(5);
    cacheItemWriter.gereplacedems().forEach(p -> replacedertThat(p.getFirstName()).isEqualTo(p.getFirstName().toLowerCase()));
    cacheItemWriter.clear();
    startJob(Optional.of("D"), Optional.of(true));
    replacedertThat(cacheItemWriter.gereplacedems()).hreplacedize(2);
    cacheItemWriter.gereplacedems().forEach(p -> replacedertThat(p.getFirstName()).isEqualTo(p.getFirstName().toUpperCase()));
    cacheItemWriter.clear();
    startJob(Optional.of("To"), Optional.of(false));
    replacedertThat(cacheItemWriter.gereplacedems()).hreplacedize(3);
    cacheItemWriter.gereplacedems().forEach(p -> replacedertThat(p.getFirstName()).isEqualTo(p.getFirstName().toLowerCase()));
}

18 Source : JobLauncherCommandLineRunner.java
with Apache License 2.0
from yuanmabiji

private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException {
    for (Job job : this.jobs) {
        if (StringUtils.hasText(this.jobNames)) {
            String[] jobsToRun = this.jobNames.split(",");
            if (!PatternMatchUtils.simpleMatch(jobsToRun, job.getName())) {
                logger.debug("Skipped job: " + job.getName());
                continue;
            }
        }
        execute(job, jobParameters);
    }
}

18 Source : JobLauncherCommandLineRunner.java
with Apache License 2.0
from yuanmabiji

private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException {
    if (this.jobRegistry != null && StringUtils.hasText(this.jobNames)) {
        String[] jobsToRun = this.jobNames.split(",");
        for (String jobName : jobsToRun) {
            try {
                Job job = this.jobRegistry.getJob(jobName);
                if (this.jobs.contains(job)) {
                    continue;
                }
                execute(job, jobParameters);
            } catch (NoSuchJobException ex) {
                logger.debug("No job found in registry for job name: " + jobName);
            }
        }
    }
}

18 Source : JobLauncherCommandLineRunner.java
with Apache License 2.0
from yuanmabiji

protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException, JobParametersNotFoundException {
    JobParameters parameters = getNextJobParameters(job, jobParameters);
    JobExecution execution = this.jobLauncher.run(job, parameters);
    if (this.publisher != null) {
        this.publisher.publishEvent(new JobExecutionEvent(execution));
    }
}

18 Source : JobLauncherCommandLineRunner.java
with Apache License 2.0
from yuanmabiji

private JobParameters getNextJobParametersForExisting(Job job, JobParameters jobParameters) {
    JobExecution lastExecution = this.jobRepository.getLastJobExecution(job.getName(), jobParameters);
    if (isStoppedOrFailed(lastExecution) && job.isRestartable()) {
        JobParameters previousIdentifyingParameters = getGetIdentifying(lastExecution.getJobParameters());
        return merge(previousIdentifyingParameters, jobParameters);
    }
    return jobParameters;
}

18 Source : JobLauncherCommandLineRunner.java
with Apache License 2.0
from yuanmabiji

private JobParameters getNextJobParameters(Job job, JobParameters jobParameters) {
    if (this.jobRepository != null && this.jobRepository.isJobInstanceExists(job.getName(), jobParameters)) {
        return getNextJobParametersForExisting(job, jobParameters);
    }
    if (job.getJobParametersIncrementer() == null) {
        return jobParameters;
    }
    JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer).getNextJobParameters(job).toJobParameters();
    return merge(nextParameters, jobParameters);
}

18 Source : JobTaskScheduled.java
with Apache License 2.0
from xuminwlt

@Slf4j
@Component
public clreplaced JobTaskScheduled {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private Job batchJob;

    private AtomicLong count = new AtomicLong(0);

    public void run() {
        long timeCount = count.incrementAndGet();
        log.info("任务执行开始 [count={}, date={}]", timeCount, DateFormatUtil.formatDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, new Date()));
        SimpleJobLauncher launcher = new SimpleJobLauncher();
        launcher.setJobRepository(jobRepository);
        launcher.setTaskExecutor(new SimpleAsyncTaskExecutor());
        try {
            launcher.run(batchJob, new JobParameters());
        } catch (Exception e) {
            log.error("任务执行失败 [count={}, date={}]", timeCount, DateFormatUtil.formatDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, new Date()), e);
        } finally {
            log.info("任务执行结束 [count={}, date={}]", timeCount, DateFormatUtil.formatDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, new Date()));
        }
    }
}

18 Source : JobController.java
with MIT License
from wuyouzhuguli

/**
 * @author MrBird
 */
@RestController
@RequestMapping("job")
public clreplaced JobController {

    @Autowired
    private Job job;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private JobOperator jobOperator;

    @GetMapping("launcher/{message}")
    public String launcher(@PathVariable String message) throws Exception {
        JobParameters parameters = new JobParametersBuilder().addString("message", message).toJobParameters();
        // 将参数传递给任务
        jobLauncher.run(job, parameters);
        return "success";
    }

    @GetMapping("operator/{message}")
    public String operator(@PathVariable String message) throws Exception {
        // 传递任务名称,参数使用 kv方式
        jobOperator.start("job", "message=" + message);
        return "success";
    }
}

18 Source : SendCampaignController.java
with Apache License 2.0
from wultra

/**
 * Controller clreplaced storing send campaign methods
 *
 * @author Martin Tupy, [email protected]
 */
@RestController
@RequestMapping(value = "push/campaign/send")
public clreplaced SendCampaignController {

    private static final Logger logger = LoggerFactory.getLogger(SendCampaignController.clreplaced);

    private final JobLauncher jobLauncher;

    private final Job job;

    private final PushCampaignRepository pushCampaignRepository;

    private final PushMessageSenderService pushMessageSenderService;

    private final JsonSerialization jsonSerialization;

    @Autowired
    public SendCampaignController(JobLauncher jobLauncher, Job job, PushCampaignRepository pushCampaignRepository, PushMessageSenderService pushMessageSenderService, JsonSerialization jsonSerialization) {
        this.jobLauncher = jobLauncher;
        this.job = job;
        this.pushCampaignRepository = pushCampaignRepository;
        this.pushMessageSenderService = pushMessageSenderService;
        this.jsonSerialization = jsonSerialization;
    }

    /**
     * Run sending job with campaignID and timestamp parameters.
     *
     * @param id Specific campaign ID.
     * @return Response with status.
     * @throws PushServerException In case campaign with given ID is not found.
     */
    @PostMapping(value = "live/{id}")
    @Operation(summary = "Send a campaign", description = "Send message from a specific campaign to devices belonged to users replacedociated with that campaign. Whereas each device gets a campaign only once.\n" + "\n" + "If sending was successful then sent parameter is set on true and timestampSent is set on current time.")
    public Response sendCampaign(@PathVariable(value = "id") Long id) throws PushServerException {
        logger.info("Received sendCampaign request, campaign ID: {}", id);
        try {
            final Optional<PushCampaignEnreplacedy> campaignEnreplacedyOptional = pushCampaignRepository.findById(id);
            if (!campaignEnreplacedyOptional.isPresent()) {
                throw new PushServerException("Campaign with entered ID does not exist");
            }
            JobParameters jobParameters = new JobParametersBuilder().addLong("campaignId", id).addDate("timestamp", new Date()).toJobParameters();
            jobLauncher.run(job, jobParameters);
            logger.info("The sendCampaign request succeeded, campaign ID: {}", id);
            return new Response();
        } catch (JobExecutionAlreadyRunningException e) {
            throw new PushServerException("Job execution already running", e);
        } catch (JobRestartException e) {
            throw new PushServerException("Job is restarted", e);
        } catch (JobInstanceAlreadyCompleteException e) {
            throw new PushServerException("Job instance already completed", e);
        } catch (JobParametersInvalidException e) {
            throw new PushServerException("Job parameters are invalid", e);
        }
    }

    /**
     * Method for sending testing user on campaign through PushMessge sending.
     *
     * @param id Campaign ID
     * @param request Testing user ID
     * @return Response with status
     * @throws PushServerException In case request object is invalid.
     */
    @PostMapping(value = "test/{id}")
    @Operation(summary = "Send a test campaign", description = "Send message from a specific campaign on test user identified in request body, userId param, to check rightness of that campaign.")
    public Response sendTestCampaign(@PathVariable(value = "id") Long id, @RequestBody ObjectRequest<TestCampaignRequest> request) throws PushServerException {
        logger.info("Received sendTestCampaign request, campaign ID: {}", id);
        final Optional<PushCampaignEnreplacedy> campaignEnreplacedyOptional = pushCampaignRepository.findById(id);
        if (!campaignEnreplacedyOptional.isPresent()) {
            throw new PushServerException("Campaign with entered ID does not exist");
        }
        final PushCampaignEnreplacedy campaign = campaignEnreplacedyOptional.get();
        TestCampaignRequest requestedObject = request.getRequestObject();
        String errorMessage = TestCampaignRequestValidator.validate(requestedObject);
        if (errorMessage != null) {
            throw new PushServerException(errorMessage);
        }
        PushMessage pushMessage = new PushMessage();
        pushMessage.setUserId(request.getRequestObject().getUserId());
        pushMessage.setBody(jsonSerialization.deserializePushMessageBody(campaign.getMessage()));
        List<PushMessage> message = new ArrayList<>();
        message.add(pushMessage);
        pushMessageSenderService.sendPushMessage(campaign.getAppId(), message);
        logger.info("The sendTestCampaign request succeeded, campaign ID: {}", id);
        return new Response();
    }
}

18 Source : ComposedTaskRunnerConfigurationWithPropertiesTests.java
with Apache License 2.0
from spring-cloud-task-app-starters

/**
 * @author Glenn Renfro
 */
@RunWith(SpringRunner.clreplaced)
@ContextConfiguration(clreplacedes = { EmbeddedDataSourceConfiguration.clreplaced, DataFlowTestConfiguration.clreplaced, StepBeanDefinitionRegistrar.clreplaced, ComposedTaskRunnerConfiguration.clreplaced, StepBeanDefinitionRegistrar.clreplaced })
@TestPropertySource(properties = { "graph=AAA && BBB && CCC", "max-wait-time=1010", "composed-task-properties=" + COMPOSED_TASK_PROPS, "interval-time-between-checks=1100", "composed-task-arguments=--baz=boo", "dataflow-server-uri=https://bar" })
@EnableAutoConfiguration(exclude = { CommonSecurityAutoConfiguration.clreplaced })
public clreplaced ComposedTaskRunnerConfigurationWithPropertiesTests {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private Job job;

    @Autowired
    private TaskOperations taskOperations;

    @Autowired
    private ComposedTaskProperties composedTaskProperties;

    protected static final String COMPOSED_TASK_PROPS = "app.AAA.format=yyyy, " + "app.BBB.format=mm, " + "deployer.AAA.memory=2048m";

    @Test
    @DirtiesContext
    public void testComposedConfiguration() throws Exception {
        JobExecution jobExecution = this.jobRepository.createJobExecution("ComposedTest", new JobParameters());
        job.execute(jobExecution);
        Map<String, String> props = new HashMap<>(1);
        props.put("format", "yyyy");
        props.put("memory", "2048m");
        replacedertEquals(COMPOSED_TASK_PROPS, composedTaskProperties.getComposedTaskProperties());
        replacedertEquals(1010, composedTaskProperties.getMaxWaitTime());
        replacedertEquals(1100, composedTaskProperties.getIntervalTimeBetweenChecks());
        replacedertEquals("https://bar", composedTaskProperties.getDataflowServerUri().toASCIIString());
        List<String> args = new ArrayList<>(1);
        args.add("--baz=boo");
        replacedert.isNull(job.getJobParametersIncrementer(), "JobParametersIncrementer must be null.");
        verify(this.taskOperations).launch("AAA", props, args, null);
    }
}

18 Source : ComposedTaskRunnerConfigurationNoPropertiesTests.java
with Apache License 2.0
from spring-cloud-task-app-starters

/**
 * @author Glenn Renfro
 */
@RunWith(SpringRunner.clreplaced)
@ContextConfiguration(clreplacedes = { EmbeddedDataSourceConfiguration.clreplaced, DataFlowTestConfiguration.clreplaced, StepBeanDefinitionRegistrar.clreplaced, ComposedTaskRunnerConfiguration.clreplaced, StepBeanDefinitionRegistrar.clreplaced })
@TestPropertySource(properties = { "graph=AAA && BBB && CCC", "max-wait-time=1000" })
@EnableAutoConfiguration(exclude = { CommonSecurityAutoConfiguration.clreplaced })
public clreplaced ComposedTaskRunnerConfigurationNoPropertiesTests {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private Job job;

    @Autowired
    private TaskOperations taskOperations;

    @Test
    @DirtiesContext
    public void testComposedConfiguration() throws Exception {
        JobExecution jobExecution = this.jobRepository.createJobExecution("ComposedTest", new JobParameters());
        job.execute(jobExecution);
        replacedert.isNull(job.getJobParametersIncrementer(), "JobParametersIncrementer must be null.");
        verify(this.taskOperations).launch("AAA", new HashMap<>(0), new ArrayList<>(0), null);
    }
}

18 Source : SpringBatchFakerTests.java
with Apache License 2.0
from redis-developer

private <T> void run(String name, ItemReader<T> reader, ItemWriter<T> writer) throws Exception {
    TaskletStep step = stepBuilderFactory.get(name + "-step").<T, T>chunk(50).reader(reader).writer(writer).build();
    Job job = jobBuilderFactory.get(name + "-job").start(step).build();
    jobLauncher.run(job, new JobParameters());
}

18 Source : GithubJobRunner.java
with GNU General Public License v3.0
from mintster

/**
 * Created by daveburke on 11/30/16.
 */
@Component
@Conditional(GithubJobCondtion.clreplaced)
public clreplaced GithubJobRunner {

    private static final Logger logger = LoggerFactory.getLogger(GithubJobRunner.clreplaced);

    private final JobLauncher jobLauncher;

    private final Job githubJob;

    @Autowired
    public GithubJobRunner(JobLauncher jobLauncher, Job githubJob) {
        this.jobLauncher = jobLauncher;
        this.githubJob = githubJob;
    }

    @Scheduled(fixedRateString = "${github.job.fixed.delay.seconds:60}000")
    public void runGithubJob() {
        SimpleDateFormat format = new SimpleDateFormat("M-dd-yy hh:mm:ss");
        String startDateTime = format.format(new Date());
        JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).toJobParameters();
        try {
            logger.info("");
            logger.info("STARTING GITHUB BATCH JOB : " + startDateTime);
            JobExecution execution = jobLauncher.run(githubJob, jobParameters);
            logger.info("JOB STATUS  : " + execution.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("JOB FAILED!!!");
        }
    }
}

18 Source : DemoJobRunner.java
with GNU General Public License v3.0
from mintster

@Component
@Conditional(DemoJobCondition.clreplaced)
public clreplaced DemoJobRunner {

    private static final Logger logger = LoggerFactory.getLogger(DemoJobRunner.clreplaced);

    private final JobLauncher jobLauncher;

    private final Job demoJob;

    @Value("${demo.job.param.iterations}")
    long iterations;

    @Value("${demo.job.param.username}")
    String username;

    @Autowired
    public DemoJobRunner(JobLauncher jobLauncher, Job demoJob) {
        this.jobLauncher = jobLauncher;
        this.demoJob = demoJob;
    }

    @Scheduled(fixedDelayString = "${demo.job.fixed.delay.seconds:60}000")
    public void runDemoJob() {
        SimpleDateFormat format = new SimpleDateFormat("M-dd-yy hh:mm:ss");
        String startDateTime = format.format(new Date());
        JobParameters jobParameters = new JobParametersBuilder().addLong("iterations", iterations).addString("username", username).addLong("time", System.currentTimeMillis()).toJobParameters();
        try {
            logger.info("");
            logger.info("STARTING BATCH JOB AT " + startDateTime);
            JobExecution execution = jobLauncher.run(demoJob, jobParameters);
            logger.info("JOB STATUS : " + execution.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("JOB FAILED!!!");
        }
    }
}

18 Source : BatchJobConfigurationTest.java
with GNU General Public License v3.0
from michaelhoffmantech

@ContextConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.clreplaced, StepScopeTestExecutionListener.clreplaced, TransactionalTestExecutionListener.clreplaced })
@RunWith(SpringRunner.clreplaced)
@SpringBootTest(clreplacedes = PatientBatchLoaderApp.clreplaced)
@ActiveProfiles("dev")
@Transactional
public clreplaced BatchJobConfigurationTest {

    @Autowired
    private Job job;

    @Autowired
    private FlatFileItemReader<PatientRecord> reader;

    @Autowired
    private Function<PatientRecord, PatientEnreplacedy> processor;

    @Autowired
    private JpaItemWriter<PatientEnreplacedy> writer;

    @Autowired
    private PatientRepository patientRepository;

    private JobParameters jobParameters;

    @Before
    public void setUp() {
        Map<String, JobParameter> params = new HashMap<>();
        params.put(Constants.JOB_PARAM_FILE_NAME, new JobParameter("test-unit-testing.csv"));
        jobParameters = new JobParameters(params);
    }

    @Test
    public void testJobConfiguration() {
        replacedertNotNull(job);
        replacedertEquals(Constants.JOB_NAME, job.getName());
    }

    @Test
    public void testReader() throws Exception {
        StepExecution stepExecution = MetaDataInstanceFactory.createStepExecution(jobParameters);
        int count = 0;
        try {
            count = StepScopeTestUtils.doInStepScope(stepExecution, () -> {
                int numPatients = 0;
                PatientRecord patient;
                try {
                    reader.open(stepExecution.getExecutionContext());
                    while ((patient = reader.read()) != null) {
                        replacedertNotNull(patient);
                        replacedertEquals("72739d22-3c12-539b-b3c2-13d9d4224d40", patient.getSourceId());
                        replacedertEquals("Hettie", patient.getFirstName());
                        replacedertEquals("P", patient.getMiddleInitial());
                        replacedertEquals("Schmidt", patient.getLastName());
                        replacedertEquals("[email protected]", patient.getEmailAddress());
                        replacedertEquals("(805) 384-3727", patient.getPhoneNumber());
                        replacedertEquals("Hutij Terrace", patient.getStreet());
                        replacedertEquals("Kahgepu", patient.getCity());
                        replacedertEquals("ID", patient.getState());
                        replacedertEquals("40239", patient.getZip());
                        replacedertEquals("6/14/1961", patient.getBirthDate());
                        replacedertEquals("I", patient.getAction());
                        replacedertEquals("071-81-2500", patient.getSsn());
                        numPatients++;
                    }
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        fail(e.toString());
                    }
                }
                return numPatients;
            });
        } catch (Exception e) {
            fail(e.toString());
        }
        replacedertEquals(1, count);
    }

    @Test
    public void testProcessor() throws Exception {
        PatientRecord patientRecord = new PatientRecord("72739d22-3c12-539b-b3c2-13d9d4224d40", "Hettie", "P", "Schmidt", "[email protected]", "(805) 384-3727", "Hutij Terrace", "Kahgepu", "ID", "40239", "6/14/1961", "I", "071-81-2500");
        PatientEnreplacedy enreplacedy = processor.apply(patientRecord);
        replacedertNotNull(enreplacedy);
        replacedertEquals("72739d22-3c12-539b-b3c2-13d9d4224d40", enreplacedy.getSourceId());
        replacedertEquals("Hettie", enreplacedy.getFirstName());
        replacedertEquals("P", enreplacedy.getMiddleInitial());
        replacedertEquals("Schmidt", enreplacedy.getLastName());
        replacedertEquals("[email protected]", enreplacedy.getEmailAddress());
        replacedertEquals("(805) 384-3727", enreplacedy.getPhoneNumber());
        replacedertEquals("Hutij Terrace", enreplacedy.getStreet());
        replacedertEquals("Kahgepu", enreplacedy.getCity());
        replacedertEquals("ID", enreplacedy.getState());
        replacedertEquals("40239", enreplacedy.getZipCode());
        replacedertEquals(14, enreplacedy.getBirthDate().getDayOfMonth());
        replacedertEquals(6, enreplacedy.getBirthDate().getMonthValue());
        replacedertEquals(1961, enreplacedy.getBirthDate().getYear());
        replacedertEquals("071-81-2500", enreplacedy.getSocialSecurityNumber());
    }

    @Test
    public void testWriter() throws Exception {
        PatientEnreplacedy enreplacedy = new PatientEnreplacedy("72739d22-3c12-539b-b3c2-13d9d4224d40", "Hettie", "P", "Schmidt", "[email protected]", "(805) 384-3727", "Hutij Terrace", "Kahgepu", "ID", "40239", LocalDate.of(1961, 6, 14), "071-81-2500");
        StepExecution execution = MetaDataInstanceFactory.createStepExecution();
        StepScopeTestUtils.doInStepScope(execution, () -> {
            writer.write(Arrays.asList(enreplacedy));
            return null;
        });
        replacedertTrue(patientRepository.findAll().size() > 0);
    }
}

18 Source : JobLauncherCommandLineRunner.java
with Apache License 2.0
from hello-shf

protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException, JobParametersNotFoundException {
    JobParameters nextParameters = new JobParametersBuilder(jobParameters, this.jobExplorer).getNextJobParameters(job).toJobParameters();
    JobExecution execution = this.jobLauncher.run(job, nextParameters);
    if (this.publisher != null) {
        this.publisher.publishEvent(new JobExecutionEvent(execution));
    }
}

18 Source : SpringBatchIntegrationTest.java
with Apache License 2.0
from devonfw

/**
 * @param job job to configure
 * @return jobLauncherTestUtils
 */
public JobLauncherTestUtils getJobLauncherTestUtils(Job job) {
    JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
    jobLauncherTestUtils.setJob(job);
    jobLauncherTestUtils.setJobLauncher(this.jobLauncher);
    return jobLauncherTestUtils;
}

18 Source : JobLauncherWithAdditionalRestartCapabilities.java
with Apache License 2.0
from devonfw

@Override
public JobExecution run(final Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
    if (!job.isRestartable()) {
        JobParameters originalParameters = jobParameters;
        while (this.jobRepository.isJobInstanceExists(job.getName(), jobParameters)) {
            // check if batch job is still running or was completed already
            // replacedogous to SimpleJobRepository#createJobExecution
            JobExecution jobExecution = this.jobRepository.getLastJobExecution(job.getName(), jobParameters);
            if (jobExecution.isRunning()) {
                throw new JobExecutionAlreadyRunningException("A job execution for this job is already running: " + jobExecution.getJobInstance());
            }
            BatchStatus status = jobExecution.getStatus();
            if (status == BatchStatus.COMPLETED || status == BatchStatus.ABANDONED) {
                throw new JobInstanceAlreadyCompleteException("A job instance already exists and is complete for parameters=" + originalParameters + ".  If you want to run this job again, change the parameters.");
            }
            // if there is a NullPointerException executing the following statement
            // there has not been a JobParametersIncrementer set for the job
            jobParameters = job.getJobParametersIncrementer().getNext(jobParameters);
        }
    }
    return super.run(job, jobParameters);
}

18 Source : AsyncJobLauncher.java
with MIT License
from Daimler

@Override
public JobExecution run(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
    LOG.info("async run of job :{}", job.getName());
    return super.run(job, jobParameters);
}

18 Source : AdHocSchedulerTest.java
with Apache License 2.0
from chrisgleissner

@Test
public void scheduleWithJobConfigAndDateWorks() throws InterruptedException {
    Job job1 = job("j1", latch1);
    Job job2 = job("j2", latch2);
    jobBuilder.registerJob(job1);
    jobBuilder.registerJob(job2);
    JobConfig job1Config = JobConfig.builder().name("j1").build();
    JobConfig job2Config = JobConfig.builder().name("j2").build();
    Date oneSecondFromNow = Date.from(Instant.now().plusMillis(1000));
    scheduler.schedule(job1Config, oneSecondFromNow);
    scheduler.schedule(job2Config, oneSecondFromNow);
    scheduler.start();
    latch1.await(4, SECONDS);
    latch2.await(4, SECONDS);
    scheduler.pause();
}

18 Source : AdHocSchedulerTest.java
with Apache License 2.0
from chrisgleissner

@Test
public void scheduleWithJobConfigAndCronWorks() throws InterruptedException {
    Job job1 = job("j1", latch1);
    Job job2 = job("j2", latch2);
    jobBuilder.registerJob(job1);
    jobBuilder.registerJob(job2);
    JobConfig job2Config = JobConfig.builder().name("j2").build();
    scheduler.schedule("j1", job1, TRIGGER_EVERY_SECOND);
    scheduler.schedule(job2Config, TRIGGER_EVERY_SECOND);
    scheduler.start();
    latch1.await(4, SECONDS);
    latch2.await(4, SECONDS);
    scheduler.pause();
}

18 Source : JobBuilder.java
with Apache License 2.0
from chrisgleissner

public static Job registerJob(JobRegistry jobRegistry, Job job) {
    jobRegistry.unregister(job.getName());
    try {
        jobRegistry.register(new JobFactory() {

            @Override
            public Job createJob() {
                return job;
            }

            @Override
            public String getJobName() {
                return job.getName();
            }
        });
    } catch (Exception e) {
        throw new RuntimeException("Could not create " + job.getName(), e);
    }
    return job;
}

18 Source : AdHocStarter.java
with Apache License 2.0
from chrisgleissner

public JobExecution start(JobConfig jobConfig) {
    try {
        Job job = jobLocator.getJob(jobConfig.getName());
        jobPropertyResolvers.started(jobConfig);
        Map<String, JobParameter> params = JobParamUtil.convertRawToParamMap(jobConfig.getProperties());
        if (addUniqueJobParameter)
            params.put("uuid", new JobParameter(UUID.randomUUID().toString()));
        JobParameters jobParameters = new JobParameters(params);
        log.info("Starting {} with {}", jobConfig.getName(), jobConfig);
        JobLauncher jobLauncher = jobConfig.isAsynchronous() ? asyncJobLauncher : syncJobLauncher;
        return jobLauncher.run(job, jobParameters);
    } catch (JobExecutionException e) {
        throw new BatchRuntimeException(format("Failed to start job '%s' with %s. Reason: %s", jobConfig.getName(), jobConfig, e.getMessage()), e);
    } catch (Exception e) {
        throw new RuntimeException(format("Failed to start job '%s' with %s. Reason: %s", jobConfig.getName(), jobConfig, e.getMessage()), e);
    }
}

18 Source : DemoController.java
with Apache License 2.0
from ab-book

@RestController
public clreplaced DemoController {

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    Job importJob;

    public JobParameters jobParameters;

    @RequestMapping("/read")
    public String imp(String fileName) throws Exception {
        String path = fileName + ".csv";
        jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString("input.file.name", path).toJobParameters();
        jobLauncher.run(importJob, jobParameters);
        return "ok";
    }
}

17 Source : JobLaunchService.java
with Apache License 2.0
from ypmc

public JobResult launchJob(Job job) {
    try {
        JobParameters jobParameters = new JobParametersBuilder().addDate("timestamp", Calendar.getInstance().getTime()).toJobParameters();
        JobExecution jobExecution = jobLauncher.run(job, jobParameters);
        return JobResult.builder().jobName(job.getName()).jobId(jobExecution.getJobId()).jobExitStatus(jobExecution.getExitStatus()).timestamp(Calendar.getInstance().getTimeInMillis()).build();
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new RuntimeException("launch job exception ", e);
    }
}

17 Source : BatchServiceTest.java
with MIT License
from yidao620c

/**
 * BatchServiceTest
 *
 * @author XiongNeng
 * @version 1.0
 * @since 2018/2/2
 */
@RunWith(SpringRunner.clreplaced)
@SpringBootTest(clreplacedes = Application.clreplaced)
public clreplaced BatchServiceTest {

    private Logger logger = LoggerFactory.getLogger(this.getClreplaced());

    @Autowired
    private CommonProperties p;

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    @Qualifier("commonJob")
    private Job commonJob;

    @Autowired
    @Qualifier("vtollJob")
    private Job vtollJob;

    @Autowired
    @Qualifier("cantonJob")
    private Job cantonJob;

    @Autowired
    @Qualifier("zappJob")
    private Job zappJob;

    @Autowired
    @Qualifier("zlogJob")
    private Job zlogJob;

    @Resource
    private CsvService csvService;

    private static final String KEY_JOB_NAME = "input.job.name";

    private static final String KEY_FILE_NAME = "input.file.name";

    private static final String KEY_VO_NAME = "input.vo.name";

    private static final String KEY_COLUMNS = "input.columns";

    private static final String KEY_SQL = "input.sql";

    @Test
    public void testBudgetVtoll() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString("input.file.name", p.getCsvVtoll()).toJobParameters();
        jobLauncher.run(vtollJob, jobParameters);
        logger.info("Main线程执行完成");
        while (true) {
            Thread.sleep(2000000L);
        }
    }

    @Test
    public void testCanton() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString("input.file.name", p.getCsvCanton()).toJobParameters();
        jobLauncher.run(cantonJob, jobParameters);
        logger.info("Main线程执行完成");
        while (true) {
            Thread.sleep(2000000L);
        }
    }

    /**
     * 测试一个配置类,可同时运行多个任务
     * @throws Exception 异常
     */
    @Test
    public void testCommonJobs() throws Exception {
        JobParameters jobParameters1 = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString(KEY_JOB_NAME, "App").addString(KEY_FILE_NAME, p.getCsvApp()).addString(KEY_VO_NAME, "com.xncoding.trans.modules.zapp.App").addString(KEY_COLUMNS, String.join(",", new String[] { "appid", "zname", "flag" })).addString(KEY_SQL, "insert into z_test_App (appid, zname, flag) values(:appid, :zname, :flag)").toJobParameters();
        jobLauncher.run(commonJob, jobParameters1);
        JobParameters jobParameters2 = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString(KEY_JOB_NAME, "Log").addString(KEY_FILE_NAME, p.getCsvLog()).addString(KEY_VO_NAME, "com.xncoding.trans.modules.zlog.Log").addString(KEY_COLUMNS, String.join(",", new String[] { "logid", "msg", "logtime" })).addString(KEY_SQL, "insert into z_test_Log (logid, msg, logtime) values(:logid, :msg, :logtime)").toJobParameters();
        jobLauncher.run(commonJob, jobParameters2);
        logger.info("Main线程执行完成");
        while (true) {
            Thread.sleep(2000000L);
        }
    }

    /**
     * 一起测试4个CSV文件导入
     * @throws Exception 异常
     */
    @Test
    public void testImportCsv4() throws Exception {
        JobParameters jobParameters1 = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString(KEY_JOB_NAME, "BscExeOffice").addString(KEY_FILE_NAME, p.getCsvExeOffice()).addString(KEY_VO_NAME, "com.xncoding.trans.modules.common.vo.BscExeOffice").addString(KEY_COLUMNS, String.join(",", new String[] { "id", "cantonid", "code", "name", "memcode", "supdeptid", "comdeptid", "contactman", "tel", "mobil", "email", "bgofficeid", "infomobil", "infoman", "logpreplaced", "startdate", "stopdate", "status", "memo", "auditer", "audittime", "isaudit", "edittime", "platform_id", "isprintbill" })).addString(KEY_SQL, "insert into NT_BSC_EXEOFFICE (F_ID,F_CANTONID,F_CODE,F_NAME,F_MEMCODE,F_SUPDEPTID,F_COMDEPTID,F_CONTACTMAN,F_TEL,F_MOBIL,F_EMAIL,F_BGOFFICEID,F_INFOMOBIL,F_INFOMAN,F_LOGPreplaced,F_STARTDATE,F_STOPDATE,F_STATUS,F_MEMO,F_AUDITER,F_AUDITTIME,F_ISAUDIT,F_EDITTIME,F_PLATFORM_ID,F_ISPRINTBILL)" + " values(:id, :cantonid, :code, :name, :memcode, :supdeptid, :comdeptid, :contactman, :tel, :mobil, :email, :bgofficeid, :infomobil, :infoman, :logpreplaced, :startdate, :stopdate, :status, :memo, :auditer, :audittime, :isaudit, :edittime, :platform_id, :isprintbill)").toJobParameters();
        jobLauncher.run(commonJob, jobParameters1);
        // JobParameters jobParameters2 = new JobParametersBuilder()
        // .addLong("time",System.currentTimeMillis())
        // .addString(KEY_JOB_NAME, "Log")
        // .addString(KEY_FILE_NAME, p.getCsvLog())
        // .addString(KEY_VO_NAME, "com.xncoding.trans.modules.zlog.Log")
        // .addString(KEY_COLUMNS, String.join(",", new String[]{
        // "logid", "msg", "logtime"
        // }))
        // .addString(KEY_SQL, "insert into z_test_Log (logid, msg, logtime) values(:logid, :msg, :logtime)")
        // .toJobParameters();
        // jobLauncher.run(commonJob, jobParameters2);
        logger.info("Main线程执行完成");
        while (true) {
            Thread.sleep(2000000L);
        }
    }

    /**
     *        CREATE TABLE Z_TEST_APP (
     *            appid INT,
     *            zname VARCHAR2 (20),
     *            flag VARCHAR2 (2),
     *            CONSTRAINT app_pk PRIMARY KEY (appid)
     *         );
     *
     *         CREATE TABLE Z_TEST_LOG (
     *            logid INT,
     *            msg VARCHAR2 (20),
     *            logtime VARCHAR2 (8),
     *            CONSTRAINT log_pk PRIMARY KEY (logid)
     *         );
     * @throws Exception
     */
    @Test
    public void testTwoJobs() throws Exception {
        JobParameters jobParameters1 = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString("input.file.name", p.getCsvApp()).toJobParameters();
        jobLauncher.run(zappJob, jobParameters1);
        JobParameters jobParameters2 = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString("input.file.name", p.getCsvLog()).toJobParameters();
        jobLauncher.run(zlogJob, jobParameters2);
        logger.info("Main线程执行完成");
        while (true) {
            Thread.sleep(2000000L);
        }
    }

    @Test
    public void testRunSimple() throws Exception {
        csvService.runTask(BscCanton.clreplaced);
        csvService.runTask(BscOfficeExeItem.clreplaced);
        csvService.runTask(BscExeOffice.clreplaced);
        csvService.runTask(BscTollItem.clreplaced);
        while (true) {
            Thread.sleep(200000L);
        }
    }
}

17 Source : CsvService.java
with MIT License
from yidao620c

@Service
public clreplaced CsvService {

    private Logger logger = LoggerFactory.getLogger(this.getClreplaced());

    @Resource
    private CommonProperties p;

    @Resource
    private JobLauncher jobLauncher;

    @Resource
    @Qualifier("commonJob")
    private Job commonJob;

    private static final String KEY_JOB_NAME = "input.job.name";

    private static final String KEY_FILE_NAME = "input.file.name";

    private static final String KEY_VO_NAME = "input.vo.name";

    private static final String KEY_COLUMNS = "input.columns";

    private static final String KEY_SQL = "input.sql";

    /**
     * 导入数据库数据
     * @throws Exception ex
     */
    public void importTables() throws Exception {
        runTask(BscCanton.clreplaced);
        runTask(BscOfficeExeItem.clreplaced);
        runTask(BscExeOffice.clreplaced);
        runTask(BscTollItem.clreplaced);
    }

    /**
     * 根据类名反射运行相应的任务
     *
     * @param c 定义的Bean类
     */
    public void runTask(Clreplaced c) throws Exception {
        TableName a = (TableName) c.getAnnotation(TableName.clreplaced);
        String tableName = a.value();
        Field[] fields = c.getDeclaredFields();
        List<String> fieldNames = new ArrayList<>();
        List<String> paramNames = new ArrayList<>();
        for (Field f : fields) {
            fieldNames.add(f.getName());
            paramNames.add(":" + f.getName());
        }
        String columnsStr = String.join(",", fieldNames);
        String paramsStr = String.join(",", paramNames);
        String csvFileName;
        if (p.getLocation() == 1) {
            csvFileName = p.getCsvDir() + tableName + ".csv";
        } else {
            csvFileName = tableName + ".csv";
        }
        JobParameters jobParameters1 = new JobParametersBuilder().addLong("time", System.currentTimeMillis()).addString(KEY_JOB_NAME, tableName).addString(KEY_FILE_NAME, csvFileName).addString(KEY_VO_NAME, c.getCanonicalName()).addString(KEY_COLUMNS, String.join(",", fieldNames)).addString(KEY_SQL, "insert into " + tableName + " (" + columnsStr + ")" + " values(" + paramsStr + ")").toJobParameters();
        jobLauncher.run(commonJob, jobParameters1);
    }
}

17 Source : CheckDomainTask.java
with GNU General Public License v3.0
from memphisx

/**
 * Created by Kyriakos Bompotis on 9/6/20.
 */
@Component
public clreplaced CheckDomainTask {

    private static final Logger log = LoggerFactory.getLogger(CheckDomainTask.clreplaced);

    private final JobLauncher jobLauncher;

    private final Job checkDomainsStatusJob;

    private final Job generateHourlyMetricsJob;

    private final Job generateDailyMetricsJob;

    private final Job generateWeeklyMetricsJob;

    private final Job cleanUpDomainChecksJob;

    @Value("${settings.schedulers.cleanup.enabled:false}")
    private Boolean cleanupEnabled;

    @Autowired
    public CheckDomainTask(JobLauncher jobLauncher, Job checkDomainsStatusJob, Job generateHourlyMetricsJob, Job generateDailyMetricsJob, Job generateWeeklyMetricsJob, Job cleanUpDomainChecksJob) {
        this.jobLauncher = jobLauncher;
        this.checkDomainsStatusJob = checkDomainsStatusJob;
        this.generateHourlyMetricsJob = generateHourlyMetricsJob;
        this.generateDailyMetricsJob = generateDailyMetricsJob;
        this.generateWeeklyMetricsJob = generateWeeklyMetricsJob;
        this.cleanUpDomainChecksJob = cleanUpDomainChecksJob;
    }

    @Scheduled(cron = "0 0 0 2 * *")
    public void deleteOldDomainChecks() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        if (cleanupEnabled) {
            JobParameters params = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
            jobLauncher.run(cleanUpDomainChecksJob, params);
        } else {
            log.info("Cleanup scheduler is disabled. Skipping cleanup.");
        }
    }

    @Scheduled(cron = "0 * * * * *")
    public void checkDomains() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        JobParameters params = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
        jobLauncher.run(checkDomainsStatusJob, params);
    }

    @Scheduled(cron = "0 0 * * * *")
    public void hourlyMetrics() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        JobParameters params = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
        jobLauncher.run(generateHourlyMetricsJob, params);
    }

    @Scheduled(cron = "0 0 0 * * *")
    public void dailyMetrics() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        JobParameters params = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
        jobLauncher.run(generateDailyMetricsJob, params);
    }

    @Scheduled(cron = "0 0 0 * * 0")
    public void weeklyMetrics() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        JobParameters params = new JobParametersBuilder().addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
        jobLauncher.run(generateWeeklyMetricsJob, params);
    }
}

17 Source : ScheduleJobLauncherServiceTest.java
with MIT License
from Daimler

public clreplaced ScheduleJobLauncherServiceTest {

    private static final String MOCKED_PARAM_BUILDER_SECHUB_UUID = "PARAM_UUID";

    private ScheduleJobLauncherService serviceToTest;

    private SecHubJobRepository jobRepository;

    private AsyncJobLauncher asyncJobLauncher;

    private JobExecution execution;

    private ScheduleSecHubJob secHubJob;

    private UUID uuid;

    private Job job;

    private DomainMessageService eventBus;

    private SecHubBatchJobParameterBuilder parametersbuilder;

    @Before
    public void before() throws Exception {
        serviceToTest = new ScheduleJobLauncherService();
        uuid = UUID.randomUUID();
        parametersbuilder = mock(SecHubBatchJobParameterBuilder.clreplaced);
        jobRepository = mock(SecHubJobRepository.clreplaced);
        asyncJobLauncher = mock(AsyncJobLauncher.clreplaced);
        execution = mock(JobExecution.clreplaced);
        job = mock(Job.clreplaced);
        eventBus = mock(DomainMessageService.clreplaced);
        serviceToTest.jobLauncher = asyncJobLauncher;
        serviceToTest.job = job;
        serviceToTest.eventBus = eventBus;
        serviceToTest.parameterBuilder = parametersbuilder;
        secHubJob = mock(ScheduleSecHubJob.clreplaced);
        when(secHubJob.getUUID()).thenReturn(uuid);
        when(asyncJobLauncher.run(any(Job.clreplaced), any(JobParameters.clreplaced))).thenReturn(execution);
        JobParameters fakeJobParams = mock(JobParameters.clreplaced);
        when(fakeJobParams.getString(BATCHPARAM_SECHUB_UUID)).thenReturn(MOCKED_PARAM_BUILDER_SECHUB_UUID);
        when(parametersbuilder.buildParams(any())).thenReturn(fakeJobParams);
    }

    @Test
    public void executeJob__calls_job_launcher_with_job_uuid_as_parameter() throws Exception {
        /* prepare */
        UUID jobUUID = UUID.randomUUID();
        ScheduleSecHubJob secHubJob = mock(ScheduleSecHubJob.clreplaced);
        when(secHubJob.getJsonConfiguration()).thenReturn("jsonConfig");
        when(secHubJob.getUUID()).thenReturn(jobUUID);
        when(jobRepository.findNextJobToExecute()).thenReturn(Optional.of(secHubJob));
        /* execute */
        serviceToTest.executeJob(secHubJob);
        /* test */
        ArgumentCaptor<JobParameters> captor = ArgumentCaptor.forClreplaced(JobParameters.clreplaced);
        verify(asyncJobLauncher).run(any(Job.clreplaced), captor.capture());
        String sechubUUID = captor.getValue().getString(BATCHPARAM_SECHUB_UUID);
        replacedertEquals(MOCKED_PARAM_BUILDER_SECHUB_UUID, sechubUUID);
    }

    @Test
    public void executeJob__sends_domain_message_about_JOB_STARTED() throws Exception {
        /* prepare */
        UUID jobUUID = UUID.randomUUID();
        ScheduleSecHubJob secHubJob = mock(ScheduleSecHubJob.clreplaced);
        when(secHubJob.getJsonConfiguration()).thenReturn("jsonConfig");
        when(secHubJob.getUUID()).thenReturn(jobUUID);
        when(jobRepository.findNextJobToExecute()).thenReturn(Optional.of(secHubJob));
        /* execute */
        serviceToTest.executeJob(secHubJob);
        /* test */
        ArgumentCaptor<DomainMessage> message = ArgumentCaptor.forClreplaced(DomainMessage.clreplaced);
        verify(eventBus).sendAsynchron(message.capture());
        replacedertEquals(MessageID.JOB_STARTED, message.getValue().getMessageId());
    }
}

17 Source : CapitalizeNamesJobScheduler.java
with MIT License
from code-not-found

@EnableScheduling
@Component
public clreplaced CapitalizeNamesJobScheduler {

    private static final Logger LOGGER = LoggerFactory.getLogger(CapitalizeNamesJobScheduler.clreplaced);

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job capitalizeNamesJob;

    private boolean enabled = false;

    @Scheduled(cron = "0/10 * * * * ?")
    public void runBatchJob() throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
        LOGGER.info("start runBatchJob");
        if (enabled) {
            jobLauncher.run(capitalizeNamesJob, new JobParametersBuilder().addDate("date", new Date()).toJobParameters());
        }
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

17 Source : QuartzJobLauncher.java
with Apache License 2.0
from chrisgleissner

@Override
protected void executeInternal(JobExecutionContext context) {
    String jobName = null;
    try {
        JobDetail jobDetail = context.getJobDetail();
        JobParameters jobParams = new JobParameters();
        if (jobDetail instanceof JobParamsDetail) {
            jobParams = JobParamUtil.convertRawToJobParams(((JobParamsDetail) jobDetail).getRawJobParameters());
        }
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();
        jobName = dataMap.getString(JOB_NAME);
        JobLocator jobLocator = (JobLocator) context.getScheduler().getContext().get(JOB_LOCATOR);
        JobLauncher jobLauncher = (JobLauncher) context.getScheduler().getContext().get(JOB_LAUNCHER);
        Job job = jobLocator.getJob(jobName);
        log.info("Starting {}", job.getName());
        JobExecution jobExecution = jobLauncher.run(job, jobParams);
        log.info("{}_{} was completed successfully", job.getName(), jobExecution.getId());
    } catch (Exception e) {
        log.error("Job {} failed", jobName, e);
    }
}

17 Source : RestTest.java
with Apache License 2.0
from chrisgleissner

@Before
public void setUp() throws InterruptedException {
    if (firstExecution.compareAndSet(true, false)) {
        Job job = jobBuilder.createJob(JOB_NAME, propertyResolver -> {
            String propertyValue = propertyResolver.getProperty(PROPERTY_NAME);
            propertyValues.add(propertyValue);
            String exceptionMessage = propertyResolver.getProperty(EXCEPTION_MESSAGE_PROPERTY_NAME);
            if (exceptionMessage != null)
                throw new RuntimeException(exceptionMessage);
            jobExecutedOnce.countDown();
        });
        adHocScheduler.schedule(JOB_NAME, job, CRON_EXPRESSION);
        adHocScheduler.start();
        jobExecutedOnce.await(2, SECONDS);
        adHocScheduler.pause();
    }
}

17 Source : RestTest.java
with Apache License 2.0
from chrisgleissner

@Before
public void setUp() {
    if (firstExecution.compareAndSet(true, false)) {
        Job job = jobBuilder.createJob(JOB_NAME, propertyResolver -> {
            String propertyValue = propertyResolver.getProperty(PROPERTY_NAME);
            propertyValues.add(propertyValue);
            String exceptionMessage = propertyResolver.getProperty(EXCEPTION_MESSAGE_PROPERTY_NAME);
            if (exceptionMessage != null)
                throw new RuntimeException(exceptionMessage);
            jobExecutedOnce.countDown();
        });
        jobBuilder.registerJob(job);
    }
}

See More Examples