springboot schedule

来源:互联网 发布:小学同步教学软件 编辑:程序博客网 时间:2024/06/10 01:22

1.在application.properties配置文件中添加

#延迟5秒

jobs.fixedDelay=5000

#每隔2秒
jobs.cron=*/2 * * * * ?

2.新建一个ScheduleTask类

import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class ScheduleTask {  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");  @Scheduled(fixedDelayString = "${jobs.fixedDelay}")  public void getTask1() {    System.out.println("延迟5秒,当前时间:" + dateFormat.format(new Date()));  }  @Scheduled(cron = "${jobs.cron}")  public void getTask2() {    System.out.println("每隔2秒执行一次,当前时间:" + dateFormat.format(new Date()));  }}
3.在springboot启动类中添加启动schedule注解,如下

import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableSchedulingpublic class SpringbootApplication {   public static void main(String[] args) {     SpringApplication app=new SpringApplication(SpringbootApplication.class); app.run(args);   }}

4.启动之后效果如下