SpringBoot整合定时任务与异步任务

定时任务

1、@EnableScheduling 开启定时任务
2、@Scheduled 开启一个定时任务

Cron表达式:Cron - 在线Cron表达式生成器

1、Spring中6位组成,不允许第7位的年,顺序:秒 分 时 日 月 周 
2、在周几的位置,1-7代表周一到周日:MON-SUN
3、定时任务不应该阻塞。默认是阻塞
        1)、可以让业务运行以异步的方式,自己提交到线程池 CompletableFuture
        2)、支持定时任务线程池  task.scheduling.pool.size=5

package com.hdb.pingmoweb.seckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@EnableScheduling
public class HelloSchedule {

    @Scheduled(cron = "* * * ? * 1")
    public void hello() throws InterruptedException {
        log.info("hello...");
    }

}

异步任务

1、@EnableAsync 开启异步任务功能

2、@Async 给希望异步执行的方法上标注

使用要配置task任务线程池大小

spring:
  task:
    execution:
      pool:
        core-size: 20
        max-size: 50
package com.hdb.pingmoweb.seckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@EnableAsync
@EnableScheduling
public class HelloSchedule {

    @Async
    @Scheduled(cron = "* * * ? * 1")
    public void hello() throws InterruptedException {
        log.info("hello...");
    }

}

@EnableAsync,@EnableScheduling 多个Schedule类只需要开启一次,通常写个配置类ScheduledConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync
@EnableScheduling
@Configuration
public class ScheduledConfig {

}

你可能感兴趣的:(spring,spring,boot,java,spring)