栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot 定时任务 Scheduled(1. fixedDelay 2. fixedRate 3. initialDelay 4. cron Scheduled)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot 定时任务 Scheduled(1. fixedDelay 2. fixedRate 3. initialDelay 4. cron Scheduled)

Api说明

  1. fixedDelay
    上一次执行完毕时间点之后多长时间再执行。如:
@Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
  1. fixedRate
    上一次开始执行时间点之后多长时间再执行。如:
@Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行
  1. initialDelay
    第一次延迟多长时间后再执行。如:
@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,
之后按fixedRate的规则每5秒执行一次
  1. cron
    该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每一个域代表一个含义。
    cron在线生成器
    https://www.bejson.com/othertools/cron/

具体应用

package com.beiyou.Schedule;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ScheduledDemo {
 //每五秒执行一次
    @Scheduled(fixedRate = 5000)
    public void fixedRate(){
        log.info("fixedRate开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
        ThreadUtil.safeSleep(8000);
        log.info("fixedRate结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
    }

    //上次执行完成之后5秒再执行
    @Scheduled(fixedDelay = 5000)
    public void fixedDelay(){
        log.info("fixedDelay开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
        ThreadUtil.safeSleep(8000);
        log.info("fixedDelay结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
    }

  //第一次执行的时候延迟initalDelay秒,然后每次完成之后,fixedDeLay在执行
  @Scheduled(initialDelay = 2000,fixedDelay = 3000)
    public void initialDelay(){
        log.info("initialDelay开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
        ThreadUtil.safeSleep(8000);
        log.info("initialDelay结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
    }

//通过core表达式执行任务
    @Scheduled(cron = "0/5 * * * * ?")
    public void cron(){
        log.info(" cron开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
        ThreadUtil.safeSleep(8000);
        log.info(" cron结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
    }
}

启动类加入@EnableScheduling

package com.beiyou;

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

@SpringBootApplication
@EnableScheduling
public class App {

    public static void main(String[] args) {
      SpringApplication.run(App.class, args);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/981456.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号