1、定时任务使用场景

客户生日发邮件,定时统计报表等。

2、定时任务实现的集中方式

		1、常见定时任务 Java自带的java.util.Timer类
			timer:配置比较麻烦,时间延后问题
			timertask:不推荐

		2、Quartz框架
			配置更简单
			xml或者注解

		3、SpringBoot使用注解方式开启定时任务
			1)启动类里面 @EnableScheduling开启定时任务,自动扫描
			2)定时任务业务类 加注解 @Component被容器扫描
			3)定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期(每2s)执行一次
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication //一个注解顶下面3个
@EnableScheduling	//开启定时任务
public class FbiaoApplication {

	public static void main(String[] args) {
		SpringApplication.run(FbiaoApplication.class, args);
	}
}
@Component
public class TestTask {
	@Scheduled(fixedRate=2000) //两秒执行一次
	public void sum(){
		System.out.println("当前时间:"+new Date());
	}
}

3、SpringBoot常用定时任务表达式配置和在线生成器

案例1:

cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒
crontab 工具 https://tool.lu/crontab/
百度各种使用方法spring crontab

    @Scheduled(cron="*/1 * * * * *")//每秒执行一次
    public void testTask(){
        System.out.println("当前时间"+new Date());
    }

案例2:

fixedRate: 定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
fixedDelay: 上一次执行结束时间点后xx秒再次执行
==注意以下两种时间间隔区别 ==

    @Scheduled(fixedRate = 2000) //等价(fixedRateString="2000")字符串形式
    public void testTask() throws InterruptedException {
        Thread.sleep(4000L);
        System.out.println("当前时间"+new Date());
    }

    @Scheduled(fixedDelay = 2000) //与 fixedDelayString=“2000”等价(字符串形式)
    public void testTask() throws InterruptedException {
        Thread.sleep(4000L);
        System.out.println("当前时间"+new Date());
    }

常用cron表达式

0 0 10,14,16 * * ? 每天上午10点,下午2点,40 0/30 9-17 * * ? 朝九晚五工作时间内每半小时 
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/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:102: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触发

更多推荐

SpringBoot定时任务schedule(整理一)