在spring中使用定時器比較簡單。首先在配置文件中加入@EnableScheduling,就能夠使用註解驅動定時任務的機制,然後可以用過註解@Scheduled去配置如何定時。
目錄
1.啓動類配置(一啓動就會開始執行週期任務)
package com.lin.scheduledemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class ScheduleDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleDemoApplication.class, args);
}
}
2.定時任務(週期任務時間配置的格式:關於spring定時任務時間配置)
package com.lin.scheduledemo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* 測試簡易定時任務
* */
@Service
public class ScheduleServiceImpl {
/**計數器*/
private int count1 = 1;
private int count2 = 1;
/**每隔一秒執行一次*/
@Scheduled(fixedRate = 1000)
public void job1() {
System.out.println("【" + Thread.currentThread().getName() + "】"
+ "【job1】每秒鐘執行一次,執行第【" + count1 + "】次");
count1++;
}
/**
* 配置每天14:25:00執行
*
* 秒 分 時 天 月 星期 年 其中年是一個可以不配置的元素
* 如 0 0 0 ? * WED 表示每個星期三 0點整
* */
@Scheduled(cron = "0 25 14 * * *")
public void job2() {
System.out.println("【" + Thread.currentThread().getName() + "】"
+ "【job2】每天14:25:00執行,執行第【" + count2 + "】次");
count2++;
}
}