主要用的是这个注解@EnableScheduling
package example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableScheduling
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
package example;
//日期转换方式
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
//计划任务声明
//spring组件注解
@Component
public class SchedulerService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate=5000)
public void proFixCurrentTime()
{
System.out.println("每5秒钟执行一次:" + dateFormat.format(new Date()));
}
@Scheduled(cron="0 38 09 ? * *") //9:38:00执行
public void cornCurrentTime()
{
System.out.println("自定执行时间: " + dateFormat.format(new Date()));
}
}