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

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

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

还是不可能使用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());
        }
    }

}


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

@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()方法将根据定义的时间表继续执行

排程类型


固定费率计划


  可以使用execute()参数将fixedRate方法安排为以固定间隔运行。

@Scheduled(fixedRate = 2000)


固定延迟调度


  使用execute()参数,可以安排fixedDelay方法在最后一次调用完成与下一次调用之间具有固定的延迟运行。

@Scheduled(fixedDelay = 2000)


具有初始延迟和固定速率/固定延迟的调度


  带有initialDelayfixedRatefixedDelay参数可延迟第一次执行。

@Scheduled(fixedRate = 2000, initialDelay = 5000)


@Scheduled(fixedDelay= 2000, initialDelay = 5000)


用cron计划


  可以使用execute()参数将cron方法安排为基于cron表达式运行。

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

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

10-12 20:29