SpringBoot 中使用计划任务

在 SpringBoot 中使用 @Scheduled 十分简单,只需在方法上加上 @Scheduled 注释即可。

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

@Component
public class XXXTask {

    @Scheduled(fixedDelay = 60 * 1000)
    @Transactional
    public void run() {
        // 省略部分代码
    }

}
public @interface Scheduled {
    String cron() default ""; // cron 表达式

    String zone() default ""; // 时区

    long fixedDelay() default -1L; // 上一次执行完毕后等待毫秒数后执行

    String fixedDelayString() default "";

    long fixedRate() default -1L; // 上一次开始执行后等待毫秒数后执行

    String fixedRateString() default "";

    long initialDelay() default -1L; // 第一次在项目启动成功后等待毫秒数执行

    String initialDelayString() default "";
}

fixedDelayString fixedRateString initialDelayString 后面加 String 的意义

源码位置:org/springframework/spring-context/5.0.5.RELEASE/spring-context-5.0.5.RELEASE.jar!/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.class:240

private static long parseDelayAsLong(String value) throws RuntimeException {
    return value.length() <= 1 || !isP(value.charAt(0)) && !isP(value.charAt(1)) ? Long.parseLong(value) : Duration.parse(value).toMillis();
}

private static boolean isP(char ch) {
    return ch == 'P' || ch == 'p';
}

猜你喜欢

转载自www.cnblogs.com/StarUDream/p/9045545.html