一.异步任务
示例
controller
package com.miracle.springboot.controller;
import com.miracle.springboot.service.AsynService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsynController {
@Autowired
AsynService asynService;
@GetMapping("/hello")
public String hello(){
// 模拟用户发送 /hello 请求,然后controller调用业务层一个很耗时的方法,如果同步执行,那么页面将会很久才能得到响应
asynService.hello();
return "success";
}
}
service
package com.miracle.springboot.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsynService {
// 异步注解,标明这个方法异步执行
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中");
}
}
main方法
package com.miracle.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
// 开启异步注解的支持
@EnableAsync
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
二.定时任务
1.开启定时任务的支持
在 main 方法类中
package com.miracle.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
// 开启定时注解的支持
@EnableScheduling
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
2.在要执行的业务方法上添加任务
package com.miracle.springboot.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
/**
* 在方法上加 @Scheduled 注解
* initial-delay:设置web服务器启动后,要等多少毫秒开始执行定时任务
* fixed-delay:设定每隔多少毫秒执行一次定时任务
* cron:指定cron表达式
*/
@Scheduled(cron = "*/5 * * * * ?") // 每个5秒执行一次hello方法
public void hello(){
System.out.println("hello...");
}
}
3.cron表达式写法
详见
https://blog.youkuaiyun.com/qq_39013701/article/details/90668813