springbatch-JobLauncher使用

springbatch-JobLauncher使用

起男 506 2023-05-31

springbatch-JobLauncher使用

关闭执行自动任务

spring:
  batch:
    job:
      enabled: false

准备任务

@Configuration
public class JobLauncherDemo implements StepExecutionListener {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    private JobParameters jobParameters;

    @Bean
    public Job jobLauncherDemoJob(){
        return jobBuilderFactory
                .get("jobLauncherDemoJob")
                .start(jobLauncherDemoStep())
                .build();
    }
    @Bean
    public Step jobLauncherDemoStep(){
        return stepBuilderFactory
                .get("jobLauncherDemoStep")
                .listener(this)
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                        String msg = jobParameters.getString("msg");
                        System.out.println("执行任务,参数:"+msg);
                        return RepeatStatus.FINISHED;
                    }
                }).build();
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        jobParameters = stepExecution.getJobParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return null;
    }
}

任务触发

@RestController
public class MyController {

    @Autowired
    private JobLauncher jobLauncher;

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

    @SneakyThrows
    @GetMapping("run/{msg}")
    public String run(@PathVariable String msg){
        //把参数传给任务
        JobParameters parameters = new JobParametersBuilder()
                .addString("msg",msg)
                .toJobParameters();
        //启动任务
        jobLauncher.run(jobLauncherDemoJob,parameters);
        return "ok...";
    }
}