02: 定时任务

03: 邮件任务
AsyncService.java
package com.tian.asyncdemo.service;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello() {
try {
System.out.println("数据正在处理");
Thread.sleep(3000);
System.out.println("数据处理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
AsyncController.java
package com.tian.asyncdemo.controller;
import com.tian.asyncdemo.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* ClassName: AsyncController
* Description:
*
* @author Administrator
* @date 2025/6/6 19:48
*/
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello() {
asyncService.hello();
return "OK";
}
}
运行结果:
在Service的方法中使用@Async说这是一个异步方法,并在主入口上使用@EnableAsync开启异步支持
AsyncService.java
@Service
public class AsyncService {
@Async
public void hello() {
try {
System.out.println("数据正在处理");
Thread.sleep(3000);
System.out.println("数据处理完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主入口上使用@EnableAsync开启异步支持
再次测试: