源码查看



TaskScheduler 任务调度者
TaskExecutor 任务执行者
创建项目


开启定时任务注解功能 @EnableScheduling
@EnableScheduling // 开启定时任务注解功能
package com.qing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling // 开启定时任务注解功能
@EnableAsync // 开启异步注解功能
@SpringBootApplication
public class Springboot10TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot10TaskApplication.class, args);
}
}
使用测试 @Scheduled
cron表达式

package com.qing.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
public class ScheduledService {
// cron表达式:秒 分 时 日 月 周
// ?代表不确定,只有日和周使用,互为问号,日为*或数字时,周不确定为?,周为*或数字时,日不确定为?
// 每2秒执行一次
@Scheduled(cron = "0/2 * * * * ?")
public void hello() {
System.out.println("hello,执行成功" + LocalDateTime.now().toString());
}
}
