文章目录
开发环境
- pom文件
- 主启动类
- 在service类写定时任务的方法
- JDK 1.8
- springboot版本 1.5.12 springboot实现定时任务相当简单, 只需两步.
4.0.0
com.thc
springboot-04-task
0.0.1-SNAPSHOT
jar
springboot-06-task
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
1.5.12.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-mail
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
主启动类
在启动类加上如下的注解 @EnableScheduling
表示开启基于注解的定时任务
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
//开启基于注解的定时任务
@EnableScheduling
@SpringBootApplication
public class Springboot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}
}
在service类写定时任务的方法
在方法上加上@Scheduled ,表示这是一个定时任务的方法. 后面写上定时任务的表达式. 关于定时任务的表达式,可以看我另一篇文章. https://blog.csdn.net/qq_33229669/article/details/85013881 也可以在如下的网页中,进行定时任务的在线生成. 要去掉最后一位年. 因为spring的cron表达式,只支持 秒分时日月星期, 六位. 如果是七位会报错 http://cron.qqe2.com/
@Service
public class ScheduledService {
@Scheduled(cron = "* * * * * ?")
public void hello(){
System.out.println("hello ... ");
}
}
启动工程后,效果如下图