springboot 定时任务(多线程)

直接上代码:

1、定义一个配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class ScheduleConfig {

    @Value("${schedule.corePoolSize}")  // 引入yml配置
    private int corePoolSize;
    @Value("${schedule.maxPoolSize}")
    private int maxPoolSize;
    @Value("${schedule.queueCapacity}")
    private int queueCapacity;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }

}

application.yml

schedule:
  corePoolSize: 10
  maxPoolSize: 100
  queueCapacity: 10

2、定义需要按时执行的服务

corn语句在线生成器:http://cron.qqe2.com/

说明:可能会遇到定时任务一下次执行多次的情况,这是由于执行速度很快,corn语句匹配仍然生效导致的。需要修改corn语句,使其精确匹配,比如在秒位置写入0就是这个目的。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class ScheduleService {

    // 每10分钟调用一次
    @Scheduled(cron = "0 0/10 * * * ?")  // corn语句
    @Async
    public void s1() {
        // 服务1
    }

    // 每天4点调用一次
    @Scheduled(cron = "0 0 4 * * ?")
    @Async
    public void s2() {
        // 服务2
    }

}

猜你喜欢

转载自www.cnblogs.com/SamNicole1809/p/12610398.html