Languages
[Edit]
EN

Spring Boot 2 - running async tasks

4 points
Created by:
LionRanger
461

In this short article, we would like to show how to run async tasks in Spring Boot 2 application.

As async task we understand task that can be run in the separated thread.

Quick solution:

  1. add @EnableAsync annotation to the application configuration class,
  2. add @Async annotation to the application component method,
  3. call asynchronous method like normal method.

 

Practical example

In this section, you can find easy way to run some methods in async mode. Each async method should have @Async annotation. Spring Boot 2 adds to that methods proxy and runs them in executor on calls.

 

DemoApplication.java file:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

 

AsyncConfig.java file:

package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync  // <------------------------------------ REQUIRED
public class AsyncConfig { }

Hint: @EnableAsync annotation be added to any configuration.

 

TaskController.java file:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TaskController {

    @Autowired
    private TaskService taskService;

    @RequestMapping("/test")
    @ResponseBody
    public void test() throws Throwable {
        this.taskService.doTask();  // runs async task
    }
}

 

TaskService.java file:

package com.example.demo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TaskService {

    @Async  // <-------------------------------------- REQUIRED
    public void doTask() throws Throwable {
        Thread.sleep(1000);{  // replace it with some operations ...
    }
}

Warnings:

  • @Async method must be public,
  • @Async method cannot call itself.

 

Alternative titles

  1. Spring Boot 2 - execute running async tasks
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join