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触发 |