springboot schedule
程序员文章站
2024-02-29 12:01:34
...
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;
@Component
public 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
@EnableScheduling
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication app=new SpringApplication(SpringbootApplication.class);
app.run(args);
}
}
4.启动之后效果如下