gpt4 book ai didi

java - 在 Spring 批处理中重复作业(并停止、开始)

转载 作者:行者123 更新时间:2023-12-02 09:07:54 31 4
gpt4 key购买 nike

我想使用 Spring 批处理执行重复性任务。

例如,使用 Controller 停止并重新启动输出数据库表中最小值的作业。

(不必介意该步骤执行的逻辑)

或者使用 spring Batch 是不可能的吗??然后让我知道另一种方式(如@Scheduled)

@Configuration
public class someJob{

private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;

// make it repeat infinitely
@Bean
public Job job() {
return jobBuilderFactory.get("job").start(step()).build();
}

@Bean
public Step step() {
return stepBuilderFactory.get("step").tasklet(some_task).build();
}
}

-----------------------------------------------------
@RestController
@RequestMapping("/control")
public class Controller {


@PostMapping("/restart")
public void restart() {
// restart job
}

@PostMapping("/stop/{jobId}")
public void stop() {
// stop job
}
}

最佳答案

启用调度

您只需将 @EnableScheduling 注解添加到主应用程序类即可启用调度。

安排任务

计划任务就像使用 @Scheduled 注释来注释方法一样简单。

在下面的示例中,execute() 方法计划每分钟运行一次。 execute() 方法将调用所需的作业。

public class ScheduledJob {

@Setter
private boolean isJobEnabled = true;

@Autowired
private Job job;

@Autowired
private JobLauncher jobLauncher;

@Scheduled(cron = "0 * * * * *")
public void execute() throws Exception {
if (isJobEnabled) {
JobParameters jobParameters = new JobParametersBuilder().addString("time", LocalDateTime.now().toString()).toJobParameters();

JobExecution execution = jobLauncher.run(job, jobParameters);

System.out.println("Job Exit Status :: " + execution.getExitStatus());
}
}

}

isJobEnabled 的值可以使用 REST API 调用进行切换,如下所示,以启用/禁用作业的执行。

@RestController
@RequestMapping(value="/job")
public class RestController {

@Autowired
private ScheduledJob scheduledJob;

@PostMapping("/enable")
public void enable() {
scheduledJob.setJobEnabled(true);
}

@PostMapping("/disable")
public void disable() {
scheduledJob.setJobEnabled(false);
}

}

请注意,使用此方法仅限制了作业执行,但 execute() 方法将继续根据定义的计划执行

调度类型

  1. 以固定费率安排

    execute() method can be scheduled to run with a fixed interval using fixedRate parameter.

    @Scheduled(fixedRate = 2000)
  2. 固定延迟调度

    execute() method can be scheduled to run with a fixed delay between the completion of the last invocation and the start of the next, using fixedDelay parameter.

    @Scheduled(fixedDelay = 2000)
  3. 具有初始延迟和固定速率/固定延迟的调度

    initialDelay parameter with fixedRate and fixedDelay to delay the first execution.

    @Scheduled(fixedRate = 2000, initialDelay = 5000)
    @Scheduled(fixedDelay= 2000, initialDelay = 5000)
  4. 使用 cron 进行调度

    execute() method can be scheduled to run based on cron expression using cron parameter.

    @Scheduled(cron = "0 * * * * *")

关于java - 在 Spring 批处理中重复作业(并停止、开始),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59656363/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com