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;

@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.

https://github.com/xbox2204/SpringBoot-JPA-Swagger-Angular

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

@EnableAsync
@EnableScheduling

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.

    @Bean(name=thPlExectr)
    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.

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

    @Async(thPlExectr)
    @Scheduled(fixedRate = 5000)
    public void backTask(){
        log.info(Hi Vineet! I am a background task);
    }
}

Image

Leave a Reply

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