1. 月底扣話費 2. 會員到期 3. 生日祝福 4. qq好友生日祝福 5. 月底的自動發郵件給領導, 統計這個月的數據 6. 等等等
採用SpringBoot整合SpringTask不須要額外導包java
@EnableScheduling:開啓對定時任務的支持,添加在啓動類上 @Scheduled(cron="*/6 * * * * ?"):執行的方法上添加,標識方法什麼時候被執行,注意是有空格,後面詳細解釋
在啓動類上加@EnableScheduling便可開啓定時,當項目中有多個執行任務的時候,只須要開啓一次spring
@SpringBootApplication @EnableScheduling public class SpringTaskDemoApplication { publi static void main(String[] args){ SpringApplication.run(SpringTaskDemoApplication.class,args); } }
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.2.4.RELEASE</version> </dependency> </dependencies>
package com.manlu.test; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @author 漫路 */ @Component public class SchedulerTask01 { private int count = 0; //每嗝6秒執行一次 @Scheduled(cron = "*/6 * * * * ?") private void process(){ System.out.println("定時任務1:"+ ++count); } }
package com.manlu.test; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; /** * @author manlu */ @Component public class SchedulerTask02 { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedDelay = 6000) private void reportCurrentTime(){ System.out.println("定時任務2: "+DATE_FORMAT.format(new Date())); } }
//記得要在啓動器上加@EnableScheduling註解框架
上面說的那個要加空格的參數怎麼寫?如今聊一聊spring-boot
一個cron表達式至少有6個(也多是7個) 由空格分隔的時間元素。從左到右,這些元素的定義以下: 參數1:秒 0 - 59 參數2:分鐘 0 -59 參數3:小時 0 - 23 參數4:月份中的日期 0 - 30 參數5:月份 0 - 11 或 JAN - DEC 參數6:星期中的日期 1 - 7 獲取 SUN - SAT 參數7:年份 1970 - 2099 每一個元素均可以顯示的規定一個值(如6),一個區間(如9-12),一個列表(如9,11,13)或一個通配符(如*)。 「月份中的日期」 和 「星期中的日期」這兩個元素是互斥的,所以須要經過設置一個問號(?)來代表你不想設置的那個字段
表達式 | 對應的意思 |
---|---|
"0 0 10,14,16 * * ?" | 天天上午10點,下午2點,4點 時觸發 |
"0 0/30 9-17 * * ?" | 朝九晚五工做時間內每半小時,從0分開始每隔30分鐘發送一次 |
"0 0 12 ? * WED" | 表示每一個星期三中午12點 |
"0 0 12 * * ?" | 天天中午12點觸發 |
"0 15 10 ? * *" | 天天上午10:15觸發 |
"0 15 10 * * ?" | 天天上午10:15觸發 |
"0 15 10 * * ? *" | 天天上午10:15觸發 |
"0 15 10 * * ? 2005" | 2005年的天天上午10:15觸發 |
"0 * 14 * * ?" | 在天天下午2點到下午2:59期間的每1分鐘觸發 |
"0 0/55 14 * * ?" | 在天天下午2點到下午2:55期間的每5分鐘觸發 |
"0 0/55 14,18 * * ?" | 在天天下午2點到2:55期間和下午6點到6:55期間的每5分鐘觸發 |
"0 0-5 14 * * ?" | 在天天下午2點到下午2:05期間的每1分鐘觸發 |
"0 10,44 14 ? 3 WED" | 每一年三月的星期三的下午2:10和2:44觸發 |
"0 15 10 ? * MON-FRI" | 週一至週五的上午10:15觸發 |
"0 15 10 15 * ?" | 每個月15日上午10:15觸發 |
"0 15 10 L * ?" | 每個月最後一日的上午10:15觸發 |
"0 15 10 ? * 6L" | 每個月的最後一個星期五上午10:15觸發 |
"0 15 10 ? * 6L | 2002-2005" 2002年至2005年的每個月的最後一個星期五上午10:15觸發 |
"0 15 10 ? * 6#3" | 每個月的第三個星期五上午10:15觸發 |