1. 说明

  1. 默认启动单线程,进行执行定时任务。当多个任务同时进行时,只会执行一个

  2. 多任务同时执行需要指定线程池。

  3. 添加的代码放在启动类中,或者定时任务类中都可以。

2. 示例代码

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component; 
import java.time.LocalDateTime;
  
@Component
@EnableScheduling
public class ScheduleConfig {
  
    // 添加到启动类,或此处
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50);
        return taskScheduler;
    }
  
    @Scheduled(cron = "0/5 * * * * ?")
    public void execute1(){
        String curName = Thread.currentThread().getName() ;
        System.out.println("当前时间:"+LocalDateTime.now()+"  任务execute1对应的线程名: "+curName);
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
  
    @Scheduled(cron = "0/5 * * * * ?")
    public void execute2(){ 
        String curName = Thread.currentThread().getName() ;
        System.out.println("当前时间:"+LocalDateTime.now()+"  任务execute2对应的线程名: "+curName);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3. Cron表达式

转到:Cron表达式详解