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++ + "次");
}
}
该博客介绍了如何在SpringBoot应用中设置基于注解的定时任务。通过在启动类上添加@EnableScheduling注解开启定时任务功能,然后在业务类中使用@Scheduled注解定义具体的定时任务方法,如例子中每5分钟执行一次的数据统计任务。
1136

被折叠的 条评论
为什么被折叠?



