计划是在特定时间段内执行任务的过程。 Spring Boot为在Spring应用程序上编写调度程序提供了良好的支持。
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 AM开始到9:59 AM结束每分钟执行任务
package com.learnfk.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作业调度程序任务。
Fixed Rate计划程序用于在特定时间执行任务,它不等待上一个任务的完成,该值应以毫秒为单位。示例代码显示在这里-
@Scheduled(fixedRate=1000) public void fixedRateSch() { }
此处显示了用于从应用程序启动起每秒执行任务的示例代码-
package com.learnfk.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启动的应用程序,此后每执行第二个固定速率调度程序任务。
Fixed Delay调度程序用于在特定时间执行任务,它应该等待上一个任务完成,该值应以毫秒为单位。示例代码显示在这里-
@Scheduled(fixedDelay=1000, initialDelay=1000) public void fixedDelaySch() { }
在这里,initialDelay是在初始延迟值之后第一次执行任务之后的时间。
从应用程序启动完成3秒后,每秒执行一次任务的示例如下所示-
链接:https://www.learnfk.comhttps://www.learnfk.com/spring-boot/spring-boot-scheduling.html
来源:LearnFk无涯教程网
package com.learnfk.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秒,固定的延迟调度程序任务就会每秒执行一次。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)