前言:
描述一下場景:微信公衆號發送模板消息的時候需要 accesstoken,這個字段的值兩個小時以後會過期,所以需要每一個小時去請求一次accesstoken存到 redis,用的時候直接去 redis 取就行了。
這裏只把定時代碼寫出來,其他的邏輯不在這裏說。
1.springboot 自帶註解實現定時
在類上使用 @EnableScheduling 註解,在定時的方法上使用 @Scheduled()
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class ScheduleService {
private static int count = 0;
@Scheduled(fixedDelay = 1000) // 每隔 1s 執行一次
public void task() {
System.out.println(count + ":定時任務啓動,間隔 1s");
count += 1;
}
}
啓動 springboot 可以看到如下輸出:
0:定時任務啓動,間隔 1s
1:定時任務啓動,間隔 1s
2:定時任務啓動,間隔 1s
3:定時任務啓動,間隔 1s
4:定時任務啓動,間隔 1s
2.@Scheduled 傳參說明
總共有四種
- fixedDelay ,樣例中的那個,表示每隔多久執行一次,以毫秒計;這個每隔多久是包括定時函數執行的時間的,舉例:設置每隔 1 秒,定時函數執行需要 4 秒,實際運行是每 5 秒執行一次。
- cron,就是 linux 中的那個定時樣式的字符串,比較強大,用起來麻煩點,有興趣的可以研究下,這裏不講。
- fixedRate,真正意義上的每隔多久,它不會管函數本身執行需要多久,慎用
- initialDelay, 看字面意思就是第一次啓動後延遲多久的意思,需要配合其他三種一起使用,舉例:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
public class ScheduleService {
private static int count = 0;
@Scheduled(initialDelay = 2000, fixedDelay = 1000) //springboot 啓動後2s再執行定時函數
public void task() {
System.out.println(count + ":定時任務啓動,間隔 1s");
count += 1;
}
}