使用@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自帶的定時器 只適合用於簡單的定時任務/複雜的定時任務需要引入其它插件來實現