关于springboot:Spring-Boot-教程调度

16次阅读

共计 2374 个字符,预计需要花费 6 分钟才能阅读完成。

【注】本文译自:https://www.tutorialspoint.co…

  调度用来解决特定工夫周期的工作。Spring Boot 为 Spring 利用编写调度器提供了良好的反对。

Java Cron 表达式

  Java Cron 表达式用于配置 CronTrigger 实例,是 org.quartz.Trigger 的子类。对于 Java cron 表达式的更多信息可参考:https://docs.oracle.com/cd/E1…
  @EnableScheduling 注解用于使你的利用可能应用调度器。这个注解该当被加在主 Spring Boot 利用类文件中。

@SpringBootApplication
@EnableScheduling

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

  @Scheduled 注解用于触发一个特定工夫周期的调度器。

@Scheduled(cron = "0 * 9 * * ?")
public void cronJobSch() throws Exception {}

  以下代码展现了如何在每天的早上 9:00 到 9:59 之间每分钟执行工作:

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {@Scheduled(cron = "0 * 9 * * ?")
   public void cronJobSch() {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Java cron job expression::" + strDate);
   }
}

  以下截图展现了利用在 09:03:23 启动之后如何每隔一分钟执行一次:

固定频度

  固定频度调度器被用于在特定工夫执行工作。它不期待前一个工作实现,工夫单位为毫秒。示例代码如下:

@Scheduled(fixedRate = 1000)
public void fixedRateSch() {}

  以下代码示例是利用启动后的每秒钟执行一个工作:

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {@Scheduled(fixedRate = 1000)
   public void fixedRateSch() {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Fixed Rate scheduler::" + strDate);
   }
}

  观看以下截屏,能够看出利用在 09:12:00 启动后以每隔一秒钟的固定频度执行工作:

固定提早

  固定提早调度器用于在指定工夫执行工作。它该当期待上一个工作实现,单位为毫秒。示例代码如下:

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void fixedDelaySch() {}

  这里,initialDelay 是在初始化之后到首次执行间的提早值。
  上面的例子中,是从利用启动实现后 3 秒后执行每秒一次的工作:

package com.tutorialspoint.demo.scheduler;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {@Scheduled(fixedDelay = 1000, initialDelay = 3000)
   public void fixedDelaySch() {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Date now = new Date();
      String strDate = sdf.format(now);
      System.out.println("Fixed Delay scheduler::" + strDate);
   }
}

  上面看到的截屏显示的是利用在 09:18:39 启动实现 3 秒后,固定提早调度器工作每秒执行一次的状况。

正文完
 0