在springboot项目中如何使用定时任务,其实很简单,只需要两步
1、在springboot启动类添加注解@EnableScheduling开启对定时任务的支持
package com.che.pri;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、创建定时任务类,在需要定时执行的方法上添加注解@Scheduled
package com.che.pri.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTask {
@Scheduled(cron = "0 0/1 * * * ?")
public void testTask() {
System.out.println("执行了定时任务");
}
}
注意,此处定时任务类TestTask,必需添加@Component,或其他声明为spring组件的注解
3、运行程序,控制台打印如下:

本文介绍如何在SpringBoot项目中实现定时任务。首先通过在启动类添加@EnableScheduling注解来启用定时任务支持,然后创建定时任务类并在需要执行的方法上使用@Scheduled注解设置定时策略。
1941

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



