1.启用定时任务(@EnableScheduling)
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.使用@Scheduled
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Date;
/**
* Created by yawn on 2017-07-13.
*/
@Configuration
public class TaskTest {
TaskTest(){
System.out.println("construct =======>>>>>>>>>>>");
}
// fixedDelay 和 fixedDelayString 马上开始执行任务
@Scheduled(fixedDelay = 1000)
public void task() {
System.out.println("1>>>>>>>>===========");
}
@Scheduled(fixedDelayString = "2000")
public void task4() {
System.out.println("4===========>>>>>>>>");
}
// 延迟后执行任务
@Scheduled(initialDelay = 5000, fixedRate = 1000)
public void task1() {
System.out.println("2===========>>>>>>>>");
}
@Scheduled(initialDelayString = "5000", fixedRateString = "1000")
public void task3() {
System.out.println("3===========>>>>>>>>");
}
/**
* cron: A cron-like expression, extending the usual UN*X definition to include
* triggers on the second as well as minute, hour, day of month, month
* and day of week. e.g. {@code "0 * * * * MON-FRI"} means once per minute on
* weekdays (at the top of the minute - the 0th second).
*
* 这里表达式只有六位,写成七位就会报错
* 此六位分别表示 秒、分钟、小时、日、月、星期(没有年)
*/
@Scheduled(cron = "3,13,23,33 * * * * ?")
public void task2() {
System.out.println(new Date(System.currentTimeMillis()));
}
}
最后一个方法的执行结果如下:
?