1、使用的注解:
@EnableScheduling:启动类上开启基于注解的定时任务
@Scheduled:标识的方法会进行定时处理
2、启动类
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; // 开启注解版的定时任务 @EnableScheduling @SpringBootApplication public class SpringBoot11TaskApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot11TaskApplication.class, args); } }
3、业务类
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; /** * 创建定时任务 */ @Service public class ScheduledService { private static int count = 1; @Scheduled(cron = "0/5 * * * * ?") public void dataCount() { System.out.println("数据统计第" + count++ + "次"); } }