springboot基于schedule定时任务

正经学徒,佛系记录,不搞事情

基于spring3.0schedule定时任务是springboot的默认定时任务,无需再引入任何依赖,通过注解即可直接使用

启动类添加启动定时任务的注解@EnableScheduling

创建一个springbootweb工程,修改启动类

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
	public static void main(String[] args) {
		SpringApplication.run(ScheduleApplication.class, args);
	}
}

@Scheduled有两种方式设置定时任务的执行时间

  • Rate/Delay表达式

fixedRate:上一次执行的开始时间后每隔多久执行

fixedDelay:上一次执行的结束时间后每隔多久执行

initialDelay:默认程序启动时就会执行一次,该选项控制第一次在程序启动多久执行,可与上面两个联用,如

@Scheduled(initialDelay=3000, fixedRate=5000),程序启动后延迟3秒执行程序,其余的同fixedRate

  • cron表达式

corn表达式基本支持所有的定时任务情况,如几天几时几分几秒执行,无需记忆,这里提供一个自动生成cron表达式的地址:http://cron.qqe2.com/ 

上半区控制具体时间,中间段生成表达式,下半区最近5次运行时间结果

扫描二维码关注公众号,回复: 12471006 查看本文章

测试fixedRate

@Component
public class ScheduleTask {
    //设置日期格式
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void task1() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行定时任务1,时间:"+df.format(new Date()));
    }
}

结果:

这里程序睡眠了3秒,但定时任务依然是每隔5秒执行

测试fixedDelay

@Scheduled(fixedDelay = 5000)
public void task2() {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("执行定时任务2,时间:"+df.format(new Date()));
}

结果:

在程序结束后延迟3秒才会执行,所以间隔8秒

测试initialDelay

启动类添加启动时间:

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
	public static void main(String[] args) {
		SpringApplication.run(ScheduleApplication.class, args);
		//设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("系统启动时间:"+df.format(new Date()));
	}
}
@Scheduled(initialDelay = 5000,fixedRate = 2000)
public void task3() {
    System.out.println("执行定时任务3,时间:"+df.format(new Date()));
}

结果:

启动后5秒执行定时任务,之后每隔2秒执行一次

测试cron表示式:

@Scheduled(cron="*/3 * * * * ?")
public void task4() {
    System.out.println("执行定时任务4,时间:"+df.format(new Date()));
}

结果:

每3秒执行一次,具体想要的结果可以自行生成表达式

注:一个定时任务中两种方法不能联用

项目地址:

https://pan.baidu.com/s/17I-oNwP60pKk8MiRAaJqMw 提取码: xx3p

猜你喜欢

转载自blog.csdn.net/qq_31748587/article/details/85157663