java – Implement background process in Spring

java – Implement background process in Spring

You can try scheduling with Spring Schedule

Here is a official example

Technically, you enable scheduling with @EnableScheduling and annotated your task with @Scheduled(fixedRate=600000).

Another config you can used to tune your scheduler:

  • fixedRate: Execute the annotated method with a fixed period in milliseconds between invocations.

  • fixedDelay: Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

  • cron: A cron-like expression, extending the usual UN*X definition to include triggers on the second as well as minute, hour, day of month, month and day of week.

find the below sample code

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

public class AppScheduler {

    @Scheduled(fixedRate = 10000)
    public void myScheduler() {
        System.out.println(Test print);


java – Implement background process in Spring

It looks like this questions is old, but I would like to answer.
See, you can make an object of ThreadPoolTaskExecutor and assign the background process to it.
Here is my detailed code if anyone wants to see.

First thing to do would be, add these two annotation in your application starter class.


Now, create you TaskExceutor in the same class and assign it to bean with a name, so that background tasks can be created anywhere in your application and attached with this bean.

    public Executor getExecutor(){
        return new ThreadPoolTaskExecutor();

Now create a component class somewhere in the project, where you you will create the background task.
Here, you will mention the frequency with which you want your task to be exceuted. I wanted to print a statement every 5 second, you can choose your own frequency and give your own method definiton. Also, make it async and attach it with the TaskExecutor bean mentioned above, so that it doesnt interrupt the normal flow of your application.

public class BackgroundTasks {
    private static final Logger log= LoggerFactory.getLogger(BackgroundTasks.class);

    @Scheduled(fixedRate = 5000)
    public void backTask(){ Vineet! I am a background task);


Leave a Reply

Your email address will not be published. Required fields are marked *