一、Springboot异步任务


在项目开发中,绝大多数情况下都是通过同步方式处理业务逻辑的,但是比如批量处理数据,批量发送邮件,批量发送短信等操作 容易造成阻塞的情况,之前大部分都是使用多线程来完成此类任务。而在 Spring 3+ 之后,就已经内置了 @Async 注解来完美解决这个问题,从而提高效率


 


使用的注解:



  • @EnableAsync:启动类上开启基于注解的异步任务
  • @Async:标识的方法会异步执行

开启异步任务:

1.启动类添加@EnableAsync

@EnableAsync //开启基于注解的异步处理
@SpringBootApplication
public class SpringBootTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTaskApplication.class, args);
    }
}

2.批量处理方法添加@Async

@Service
public class AsyncService {
    //模拟批量处理操作
    @Async
    public void batch(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("批量处理完成.........");
    }
}

3.Controller测试

@Controller
public class AsyncController {
    @Autowired
    private AsyncService asyncService;
    @ResponseBody
    @RequestMapping("/test")
    public String test(){
        asyncService.batch();
        return "success!";
    }
}

二、Springboot定时任务调

使用注解:

  • @EnableScheduling:启动类上开启基于注解的定时任务
  • @Scheduled:标识的方法会进行定时处理

开启定时任务:

1.在启动类添加@EnableScheduling

@EnableScheduling //开启基于注解的的定时任务
@SpringBootApplication
public class SpringBootTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTaskApplication.class, args);
    }
}

2.在方法上添加@Scheduled

@Service
public class ScheduledService {
    private static int count = 0;
    //每分钟的1~10秒都调用一次
    @Scheduled(cron = "1-10 * * * * *")
    public void scheduled(){
        System.out.println("调用了scheduled() "+ ++count + " 次");
    }
}

3.运行测试

springboot 异步线程池 springboot异步任务原理_批量处理

 

corn表达式:

位置

取值范围

特殊字符

0-59

, - * /

0-59

, - * /

小时

0-23

, - * /

日期

1-31

, - * ? / L W C

月份

1-12

, - * /

星期

0-7 或 SUN-SAT 0 和 7 都是周日, 1-6 是周一到周六

, - * ? / L C #

特殊字符

代表含义

,

枚举,一个位置上指定多个值,以逗号 , 分隔

-

区间

*

任意

/

步长,每隔多久执行一次

?


日 / 星期冲突匹配 , 指定哪个值 , 另外个就是 ? ,比如: * * * ? * 1 每周 1 执行,则日用 ? 不能用 * ,不



是每一天都是周一; * * * * 2 * ? 每月 2 号 , 则星期不能用 *


L

最后

W

工作日

C

和calendar联系后计算过的值

#

这个月的第几个星期几, 4#2 ,第 2 个星期四

1-5 * * * * 1到5秒,每秒都触发任务
*/5 * * * * 每隔5秒执行一次 
0 */1 * * * 每隔1分钟执行一次 
0 0 5-15 * * 每天5-15点整点触发 
0 0-5 14 * * 在每天下午2点到下午2:05期间的每1分钟触发 
0 0/5 14 * * 在每天下午2点到下午2:55期间的每5分钟触发 
0 0/5 14,18 * * 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
0 0/30 9-17 * * 朝九晚五工作时间内每半小时 
0 0 12 ? * WED 表示每个星期三中午12点 
0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发 
0 0 23 L * ? 每月最后一天23点执行一次 
0 15 10 LW * ? 每个月最后一个工作日的10点15分0秒触发任务 
0 15 10 ? * 5#3 每个月第三周的星期五的10点15分0秒触发任务

在线生成cron表达式:http://cron.qqe2.com/