3

I'm launching a spring-batch job on application start using

spring.batch.job.names=MyJob

@Configuration
public class MyJob {
    @Bean
    public Job testJob() throws IOException {
        return jobBuilderFactory.get(MyJob.class.getSimpleName())
                .start(import())
                .build();
    }
}

Unfortunately this somehow delays the tomcat server startup. The job has a runtime of several minutes, thus I'm getting the following error:

Server Tomcat v8.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

Question: how can I run this job without preventing tomcat to start up? Eg running the job async?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

2

You can include a ServletContextListener.

Put your code in the contextInitialized method.

Andres
  • 10,561
  • 4
  • 45
  • 63
0

You can use @Scheduled annotation configured with a fixedDelay.

See the Task Execution and Scheduling in the reference for more information.

I ended up using this solution to launch a cache warm up just at startup:

private boolean isFirstTime = true;

@Scheduled(fixedDelay = 60000)
protected void refreshCachesStartup(){
    if(isFirstTime){
        // your code

        isFirstTime = false;
    }
}

EDIT: see this question for a more specific view on the argument.

Community
  • 1
  • 1
Marco Ferrari
  • 4,914
  • 5
  • 33
  • 53
  • But a `fixedDelay`would execute periodically. I only want to run the job on startup. – membersound Jan 07 '16 at 13:48
  • Hm that feels like a hack. I could as well define a very very long fixedDelay period, but maybe there is a more elegant solution to this... – membersound Jan 07 '16 at 13:59
  • AFAIK there is no built-in way to do that. You may use Spring Boot's [@ConditionalXXX](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html) annotations (or implement your own) but the base idea stay the same. – Marco Ferrari Jan 07 '16 at 15:06