首先需要在启动类上注解 @EnableScheduling
@SpringBootApplication
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
任务类:
package com.forwy.test.Tasks;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class TestJobs {
public final static long SECOND = 1 * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 固定等待时间
* @throws InterruptedException
* @auth yong.wu
*/
@Scheduled(fixedDelay = SECOND * 2)
public void fixedDelayTask() throws InterruptedException {
System.out.println("---------------------");
System.out.println("---fixed delay task--");
System.out.println("| "+sdf.format(new Date())+" |");
System.out.println("---------------------");
}
/**
* 固定时间间隔
* @auth yong.wu
*/
@Scheduled(fixedRate = SECOND * 4)
public void fixedRateTask() {
System.out.println("^^^^^^^^^^^^^^^^^^^^^");
System.out.println("---fixed rate task---");
System.out.println("| "+sdf.format(new Date())+" |");
System.out.println("^^^^^^^^^^^^^^^^^^^^^");
}
/**
* corn 表达式
* @auth yong.wu
*/
@Scheduled(cron = "0/4 * * * * ?")
public void cronTask() {
System.out.println("********************");
System.out.println("---corn rate task---");
System.out.println("| "+sdf.format(new Date())+" |");
System.out.println("********************");
}
}
结果:
---fixed delay task--
| 2017-08-25 14:26:47 |
---------------------
********************
---corn rate task---
| 2017-08-25 14:26:48 |
********************
^^^^^^^^^^^^^^^^^^^^^
---fixed rate task---
| 2017-08-25 14:26:49 |
^^^^^^^^^^^^^^^^^^^^^
---------------------
---fixed delay task--
| 2017-08-25 14:26:49 |
---------------------
---------------------
---fixed delay task--
| 2017-08-25 14:26:51 |
---------------------
********************
.
.
.