设置计划任务。
1 配置Scheduling Tasks
package sckeduling.tasks.hello;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SckeduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime(){
System.out.println("The time is now " + dateFormat.format(new Date()));
}
}
说明
The Scheduled annotation defines when a particular method runs. NOTE: This example uses fixedRate, which specifies the interval between method invocations measured from the start time of each invocation. There are other options, like fixedDelay, which specifies the interval between invocations measured from the completion of the task. You can also use @Scheduled(cron=”…”) expressions for more sophisticated task scheduling.
2 启动project
package sckeduling.tasks.hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
说明
@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.