简体   繁体   中英

Can I change Spring Batch configuration to run statically?

[Spring Batch] When @Scheduled annotation is used, it is executed dynamically. Can I change it to run statically?

Because you mention @Scheduled, I imagine your batch is executed from a web application. If you want to run it out of the box, you can:

  • use Spring boot to start your batch by launching a spring boot application: I advise you to follow this tuto and replace the example batch by your own: https://spring.io/guides/gs/batch-processing/
  • start your batch manually from a classic java application which create a spring context at start (so spring boot does the job really better)
  • start your batch as a unit test (for integration purpose): you can folow this tuto (which also use spring boot): https://www.baeldung.com/spring-batch-testing-job

Good luck

I think I misunderstood your question. If you want to run from static method there is one way to do this. You can make StaticJobInitializer component like this

@Component
public class StaticJobInitializer {

    private JobRegistry jobRegistry;
    private JobLauncher jobLauncher;

    public StaticJobInitializer(JobRegistry jobRegistry, JobLauncher jobLauncher) {
        this.jobRegistry = jobRegistry;
        this.jobLauncher = jobLauncher;
    }

    @PostConstruct
    public void init() {
        StaticJobRun.setJobRegistry(jobRegistry);
        StaticJobRun.setJobLauncher(jobLauncher);
    }
}
public final class StaticJobRun {
    private static JobRegistry jobRegistry;
    private static JobLauncher jobLauncher;

    public static JobRegistry getJobRegistry() {
        return jobRegistry;
    }

    public static JobLauncher getJobLauncher() {
        return jobLauncher;
    }

    public static void setJobLauncher(JobLauncher jobLauncher) {
        StaticJobRun.jobLauncher = jobLauncher;
    }

    public static void setJobRegistry(JobRegistry jobRegistry) {
        StaticJobRun.jobRegistry = jobRegistry;
    }
}

and than your start job static method should be like this:

public static void startJob(){
    Job job = StaticJobRun.getJobRegistry().getJob("job_name");
            JobParameters jobParameters = new JobParametersBuilder()
                    .toJobParameters();
            StaticJobRun.getJobLauncher().run(job, new JobParameters());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM