我希望能够使用REST控制器开始我的工作,然后当该工作开始时,它应该按计划运行,直到我再次使用REST停止它为止。
这是我的控制器:
@RestController public class LauncherController { @Autowired JobLauncher jobLauncher; @Autowired Job job; @RequestMapping("/launch") public String launch() throws Exception { ... jobLauncher.run(job, jobParameters); }
这是Batch conf的一部分:
@Configuration @EnableBatchProcessing @EnableScheduling public class BatchConfiguration { @Autowired public JobBuilderFactory jobBuilderFactory; @Autowired public StepBuilderFactory stepBuilderFactory; @Scheduled(cron = "0/5 * * * * ?") @Bean public Job job() { return jobBuilderFactory.get("job") .incrementer(new RunIdIncrementer()) .flow(step1()) .end() .build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1") .<Person, Person> chunk(10) .reader(reader()) .processor(processor()) .writer(writer()) .build(); }
我还设置了属性spring.batch.job.enabled = false,因为我不希望作业在Spring Boot App启动后立即运行。
现在,我可以叫我的Rest api lauch,并且作业可以运行,但只能运行一次。计划程序不起作用。我无法弄清楚我们应该在哪里定义@Scheduled Annotation ..
我会以某种方式处理它,即计划作业始终运行,但是仅当标志设置为true时,它才会执行某些操作:
@Component class ScheduledJob { private final AtomicBoolean enabled = new AtomicBoolean(false); @Scheduled(fixedRate = 1000) void execute() { if (enabled.get()) { // run spring batch here. } } void toggle() { enabled.set(!enabled.get()); } }
和一个控制器:
@RestController class HelloController { private final ScheduledJob scheduledJob; // constructor @GetMapping("/launch") void toggle() { scheduledJob.toggle(); } }