简体   繁体   中英

run process in background using spring boot

How can I run some process in background using Spring Boot? This is an example of what I need:

@SpringBootApplication
public class SpringMySqlApplication {

    @Autowired
    AppUsersRepo appRepo;

    public static void main(String[] args) {
        SpringApplication.run(SpringMySqlApplication.class, args);

        while (true) {
            Date date = new Date();
            System.out.println(date.toString());
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

You could just use the @Scheduled-Annotation.

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
     log.info("The time is now " + System.currentTimeMillis()));
}

https://spring.io/guides/gs/scheduling-tasks/ :

The Scheduled annotation defines when a particular method runs. NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation.

You can use Async behaviour. When you call the method and the current thread does wait for it to be finished.

Create a configurable class like this.

@Configuration
@EnableAsync
public class AsyncConfiguration {

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}

And then used in a method:

@Async("threadPoolTaskExecutor")
public void someAsyncMethod(...) {}

Have a look at spring documentation for more info

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