使用@Scheduled创建定时任务
package com.xyt.springboot.tasks;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component//注入spring容器
public class ScheduledTasks {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)//这个注解以毫秒为单位的,
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}
在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置
package com.xyt.springboot;
import com.xyt.springboot.config.member.MemberConfig;
import com.xyt.springboot.config.member.MemberDatasourceConfig;
import com.xyt.springboot.config.order.OrderConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling//开启任务定时器
public class AppSpringBootMybatis {
public static void main(String[] args) {
SpringApplication.run(AppSpringBootMybatis.class, args);
}
}
spring自带的定时器 只适合用于简单的定时任务/复杂的定时任务需要引入其它插件来实现