首页 > 解决方案 > 如何在启动应用程序时禁用 Job Spring Batch 的自动运行

问题描述

春季启动应用程序。在设置中,我在应用程序启动时禁用了自动运行作业(Spring Batch):

spring:
  batch:
    job:
      enabled: false

该任务计划在 75 秒后开始:

@Autowired
JobLauncher jobLauncher;
@Autowired
Job job;

@Scheduled(fixedRate = 10000000, initialDelay = 75000)
public void launchJob() throws Exception {
  JobParameters params = new JobParametersBuilder()
       .addString("JobID", String.valueOf(System.currentTimeMillis()))
       .toJobParameters();
  jobLauncher.run(job, params);
}

launch Job 方法在 75 秒后启动。但是当应用程序启动时,Spring Batch 仍然运行。由于某种原因,它忽略了设置。以下是它在 pom.xml 文件中的拼写方式:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-batch</artifactId>
</dependency>

我尝试使用 Spring Batch 创建一个单独的简单应用程序,那里一切正常,发布显然按计划进行。我不明白主应用程序中可能存在什么冲突?

标签: javaspring-bootspring-batch

解决方案


您可以在应用程序的任何位置创建一个维护标志,并在 Spring Boot 的 Application 类中添加以下方法,您可以像下面的方法一样将变量标记为 true,然后您可以根据此标志处理调度程序

@PostConstruct
public void postApplicationStarted() {
    System.out.println("Started after Spring boot application !");
    applicationStarted = true;
}



@Scheduled(fixedRate = 10000000, initialDelay = 75000)
public void launchJob() throws Exception {
  if(applicationStarted) { 
    JobParameters params = new JobParametersBuilder()
            .addString("JobID", String.valueOf(System.currentTimeMillis()))
            .toJobParameters();
    jobLauncher.run(job, params);
   }
}

推荐阅读