- spring-boot框架中集成了一個輕量級的定時器框架,配置簡單,容易上手。在spring-boot項目能夠正常啓動的前提下,保證pom文件中有如下配置:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
@Async
public class jdMessageTisk {
@Scheduled(cron = "0 0/1 * * * ?")
public void pushDataScheduled1() {
while (true) {
System.out.println("定時任務1:"+new Date());
}
}
@Scheduled(cron = "0 0/1 * * * ?")
public void pushDataScheduled2() {
while (true) {
System.out.println("定時執行2:" + new Date());
}
}
}
- 定時器執行時間使用註解@Scheduled配置,應用cron規則。
- 通過對定時參數設置,控制定時器的線程情況。新建參數類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfig {
/**
*corePoolSize:核心線程數
* 核心線程會一直存活,及時沒有任務需要執行
* 當線程數小於核心線程數時,即使有線程空閒,線程池也會優先創建新線程處理
* 設置allowCoreThreadTimeout=true(默認false)時,核心線程會超時關閉
*
* maxPoolSize:最大線程數
* 當線程數>=corePoolSize,且任務隊列已滿時。線程池會創建新線程來處理任務
* 當線程數=maxPoolSize,且任務隊列已滿時,線程池會拒絕處理任務而拋出異常
*
* queueCapacity:任務隊列容量(阻塞隊列)
* 當核心線程數達到最大時,新任務會放在隊列中排隊等待執行
*
*/
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
- 在項目啓動的application類中加入@EnableScheduling註解,引導定時任務執行
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling
@SpringBootApplication
public class EmallserverInterfaceProviderApplication {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(EmallserverInterfaceProviderApplication.class, args);
Thread.sleep(100000000l);
}
}
- 運行結果: