Springboot定时任务

Springboot定时任务

博文

spring注解@Scheduled中fixedDelay、fixedRate和cron表达式的区别

Spring Boot使用@Scheduled定时器任务

示例

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling//启用定时任务,不需要手动导入任何依赖
public class Task01Application {
    public static void main(String[] args) {
        SpringApplication.run(Task01Application.class, args);
    }
}
package com.mozq.task.task01.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/*
    1. 启动类上加@EnableScheduling,启用定时器
    2. @Scheduled设置定时任务
 */
@Component
public class Task_01 {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
    /*
        如果方法被阻塞,不会累计应该执行的次数。
     */
    @Scheduled(cron="* * * * * ?")
    public void sendOrderMessage(){
        System.out.println("发送订单消息 " + dateFormat.format(new Date()));
    }

    /*
        固定间隔执行:上次方法完成后,必须间隔fixedDelay的时间,才会再次调用。
        如果被方法调用被阻塞,等待。方法执行完毕后,间隔固定时间,再次调用方法。
    */
    @Scheduled(fixedDelay = 5000)
    public void fixedDelay(){
        System.out.println("固定延迟 " + dateFormat.format(new Date()));
    }

    /*
        固定速率:按照固定速率执行。
        如果方法被阻塞,累计阻塞时间内应该执行的次数,当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行。
     */
    int fixedRateCount = 0;
    @Scheduled(fixedRate = 3000)
    public void fixedRate(){
        if(fixedRateCount % 4 == 0){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        fixedRateCount++;
        System.out.println("固定速率" + fixedRateCount + " " + dateFormat.format(new Date()));
    }

    /*
        初次启动任务启动,延迟1秒执行。然后按照固定间隔执行。
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 7000 * 1000)
    public void getAccessToken() {
        //1.获取token和ticket
        //2.更新到数据库中
    }

}
原文地址:https://www.cnblogs.com/mozq/p/11996727.html