1. 首先通过在配置类注解@EnableScheduling 来开启对定时任务的支持,然后在要执行的定时任务方法上注解@Scheduled,声明这是一个定时任务
2. 任务执行类
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void fixedRateTime() {
System.out.println("每隔5秒执行一次:" + sf.format(new Date()));
}
@Scheduled(cron = "0 10 16 * * ?")
public void fixTime() {
System.out.println("在指定时间 " + sf.format(new Date()) + "执行");
}
}
代码解释:fixedRate 属性指每隔固定时间执行,cron 属性指按照指定时间执行,本实例指每天16点10分执行任务
3. 配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan("com.xuanwu.scheduled")
public class ScheduledConfig {
}
4. 运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(ScheduledConfig.class);
}
}