注解说明
- 使用注解:@Scheduled @EnableScheduling
- 效果:可以实现在指定时间、指定周期执行动作
引入步骤:
- 在启动方法前加上@EnableScheduling开启定时任务开关
- 在任务执行方法上加上@Scheduled,并使用cron表达式定义任务执行周期
示例代码:
package com.makai.annotations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
@Component
public class MyScheduler {
@Scheduled(cron = "0/2 * * * * ?")
public void task1() {
Calendar now = Calendar.getInstance();
System.out.println("i am task1, now:" + now.getTime().toString());
}}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
Hello world!
*
*/
@SpringBootApplication
@ComponentScan({“com.makai.annotations”})
@EnableScheduling
public class App
{
public static void main( String[] args )
{ SpringApplication.run(App.class); }
}