+
80
-

spring boot如何开启定时器?

spring boot如何开启定时器?

网友回复

+
0
-

1、现在application类中增加注解@EnableScheduling开启定时器

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

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

}

2、新建一个Scheduler类,设定时间或频率就好了

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

@Component
public class Scheduler{
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    //每隔2秒执行一次
    @Scheduled(fixedRate = 2000)
    public void testTasks() {
        System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
    }

//    //每天3:05执行
//    @Scheduled(cron = "0 05 03 ? * *")
//    public void testTasks() {
//        System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
//    }


}

我知道答案,我要回答