spring定时任务改为并行执行多个任务

1、引入pom

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

2、使用

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

import java.util.concurrent.TimeUnit;

@Configuration
@Component
@EnableScheduling
@Slf4j
public class TimerTaskTmp {
    
    

    @Scheduled(cron = "0/2 * * * * ?")
    public void task1() throws InterruptedException {
    
    
        log.info("task1 开始执行....");
        TimeUnit.SECONDS.sleep(3);
        log.info("task1 结束执行");
    }

    @Scheduled(cron = "0/2 * * * * ?")
    public void task2() throws InterruptedException {
    
    
        log.info("task2 开始执行....");
        TimeUnit.SECONDS.sleep(3);
        log.info("task2 结束执行");
    }

}

3、执行结果

在这里插入图片描述

4、支持定时任务多线程并行执行

4.1、增加配置文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

/**
 * <p>
 *  定时任务线程池
 * </p>
 */
@Configuration
public class TaskSchedulerConfig {
    
    

    @Bean
    public TaskScheduler taskScheduler() {
    
    
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50);
        return taskScheduler;
    }

}

4.2、执行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_17522211/article/details/129159765