SpringBoot任务管理
异步任务
-
创建一个springboot项目,勾选web
-
在启动类上添加@EnableAsync
package com.sheep; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; /** * @EnableAsync:开启异步注解功能 */ @EnableAsync @SpringBootApplication public class DomeApplication { public static void main(String[] args) { SpringApplication.run(DomeApplication.class, args); } }
-
创建service包在包下创建AsyncService类并添加@Async注解
package com.sheep.service; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncService { @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("数据正在处理中..."); } }
-
controller
package com.sheep.controller; import com.sheep.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"; } }
执行后会发现页面立马相应OK字符串,而后台却隔了3s才打印System.out.println("数据正在处理中...");
定时任务
-
创建springboot项目勾选web
-
在启动类中添加注解@EnableScheduling
package com.sheep; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * @EnableScheduling:开启定时任务功能 */ @EnableScheduling @SpringBootApplication public class DomeApplication { public static void main(String[] args) { SpringApplication.run(DomeApplication.class, args); } }
-
创建一个类使用cron表达式
package com.sheep.service; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class ScheduledService { /* * @Scheduled(cron="表达式") * cron = "0 53 9 * * ?" * cron = ”秒 分 时 日 月 周“ * 常用: * 0 53 9 * * ? 表示每一天的9点53分0秒执行 * 0 0/3 9,10 * * ? 表示每天9点和10点每隔3分钟执行一次 * 0 53 9 ? * 1-6 每个月的周一到周六10:15分执行 * */ @Scheduled(cron = "0/3 * * * * ?") public void hello(){ System.out.println("hello你被执行了"); } }
运行后每个相应的时间就是执行该任务