Scheduled定时任务器:是Spring 3.0以后自带的一个定时任务器
目录
Scheduled的使用
- 使用Scheduled我们首先添加其坐标
<!-- 添加 Scheduled 坐标 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
- 编写一个定时任务类
package com.zxw.scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class Scheduled {
/*** 定时任务方法 * @Scheduled:设置定时任务
* cron 属性:cron 表达式。定时任务触发是时间的一个字符串表达形式
* 这里是每2秒执行一次
*/
@org.springframework.scheduling.annotation.Scheduled(cron = "0/2 * * * * ?")
public void test(){
System.out.println("Scheduled:"+new Date());
}
}
- 在启动器中开启定时任务的使用
package com.zxw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 启动类 定时任务
*/
@SpringBootApplication
@EnableScheduling //开启定时任务
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
至此,Scheduled就能正常使用了