1. 程式人生 > 其它 >非同步任務 & 定時任務 & 郵件任務

非同步任務 & 定時任務 & 郵件任務

1.非同步任務

舉例說明:前端點擊發送郵件,返回ok,但其實後臺使用多執行緒,延時了3m在傳送

兩步:

(1)在service中告訴spring是一個非同步方法

package com.kuang.taskdemo.service;

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

@Service
public class AsyncService {

    // 告訴Spring這是一個非同步的方法
    @Async
    public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("資料正在處理...");
    }
}

  (2)主程式(有main方法的)開啟註解功能

package com.kuang.taskdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync  // 開啟非同步註解功能
@SpringBootApplication
public class TaskdemoApplication {

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

}

  其他程式碼

package com.kuang.taskdemo.controller;

import com.kuang.taskdemo.service.AsyncService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello() {
        asyncService.hello();
        return "ok";
    }
}

  

2.定時任務