Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Springboot timed tasks, case sharing for asynchronous tasks


Jun 01, 2021 Article blog


Table of contents


This article is intended to share a simple case of two springboot asynchronous tasks, timing tasks, so that everyone has a reference object.

A simple case of asynchronous tasks

When we develop projects, we often use asynchronous processing tasks, such as we send mail on the site, the background will send mail, which will cause the foreground response, until the message is sent, the response will not succeed, so we will generally take a multithreaded approach to these tasks.

  1. Create a new service package

  1. Create an AsyncService class

@Service
    public class AsyncService {

    
       public void hello(){
           try {
               Thread.sleep(3000);
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
           System.out.println("业务进行中~~");
      }
    }

  1. Create a controller package

  1. Create an AsyncController class under the controller package

@RestController
    public class AsyncController {

    
       @Autowired
       AsyncService asyncService;

    
       @GetMapping("/hello")
       public String hello(){//调用方法后会延迟3秒在页面显示Success
           asyncService.hello();
           return "success";
      }

    
    }

In this case, visit Localhost:8080/hello is: after a delay of 3 seconds, Success is output on the page and the business is being exported in the background

New problem: If you want the page to output the information “Success” directly, and let this hello method operate directly in the background with multithreaded operations, you need to add @Async annotations, so that spring boot will open a thread pool to call itself

Improvements: Annotate AsyncService

@Async//告诉Spring这是一个异步方法
    public void hello(){
       try {
           Thread.sleep(3000);
      } catch (InterruptedException e) {
           e.printStackTrace();
      }
       System.out.println("业务进行中~~");
    }

But for this annotation to work, you also need to turn on asynchronous annotation in the entry file

@EnableAsync //开启异步注解功能
@SpringBootApplication
    public class SpringbootTaskApplication {
           public static void main(String[] args) {
               SpringApplication.run(SpringbootTaskApplication.class, args);
          }
    }

At this point, test again and find that the page Success directly, but the background is still 3 seconds after the output business is in progress

A simple case for scheduled tasks

You often set up timed tasks at work, such as analyzing logs at some time of the day

So Spring provides an asynchronous way to schedule tasks, providing two interfaces.

TaskExecutor interface

TaskScheduler interface

Two notes:

• @EnableScheduling

• @Scheduled

Create a ScheduleService that writes a hello method that it executes regularly

@Service
publicclassScheduledService{


    //秒分时日月周几
    @Scheduled(cron="0 * * * * ?")
    //这里需要学习一些cron表达式的语法,明白时间如何设置,这里的意思是每当时间到0秒时就执行一次
    publicvoidhello(){
        System.out.println("hello/////");
    }
}

To use the timing feature, you also need to add a @EnableScheduling to the entry file to indicate that the timing task feature is turned on

@SpringBootApplication
    @EnableScheduling//开启定时任务注解功能
    @EnableAsync//开启异步注解功能
    publicclassSpringbootTaskApplication{

    
    publicstaticvoidmain(String[]args){
    SpringApplication.run(SpringbootTaskApplication.class,args);
    }

    
    }

The test runs and finds that hello//// is printed in the background whenever the time is 0 seconds

 Springboot timed tasks, case sharing for asynchronous tasks1

Here are two simple examples of shared students interested in SpringBoot and java to take a look at the tutorial

Java tutorial: https://www.w3cschool.cn/java/

Java Microsyscope: https://www.w3cschool.cn/minicourse/play/javaminicourse

SpringBoot tutorial: https://www.w3cschool.cn/seansblog/

SpringBoot from getting started to mastering micro lessons: https://www.w3cschool.cn/minicourse/play/springboot_my