Spring Boot Scheduled调度,调度是在特定时间段内执行任务的过程。Spring Boot 为在 Spring 应用程序上编写调度程序提供了良好的支持。
Java Cron 表达式
Java Cron 表达式用于配置 CronTrigger 的实例,CronTrigger 是 org.quartz.Trigger 的子类。有关 Java cron 表达式的更多信息,您可以参考此链接 –
https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm
@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 net.zuze.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 启动以及从该时间开始每隔一分钟执行一次 cron 作业计划程序任务。
固定频率
固定频率调度程序用于在特定时间执行任务。它不等待上一个任务的完成。这些值应以毫秒为单位。示例代码显示在这里 –
@Scheduled(fixedRate = 1000) public void fixedRateSch() { }
此处显示了从应用程序启动时每秒执行任务的示例代码 –
package net.zuze.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 net.zuze.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 秒后,固定延迟调度程序任务每秒执行一次。