在公司項(xiàng)目使用時(shí)铅忿,遇到一個(gè)問(wèn)題檩咱。系統(tǒng)由多個(gè)定時(shí)任務(wù)運(yùn)行時(shí)發(fā)現(xiàn)舀寓,當(dāng)一個(gè)線(xiàn)程阻塞(此業(yè)務(wù)循環(huán)某個(gè)條件達(dá)到后結(jié)束)所有定時(shí)任務(wù)失效,最終定位原因默認(rèn)定時(shí)任務(wù)由一個(gè)線(xiàn)程完成市埋,所以修改項(xiàng)目定時(shí)任務(wù)線(xiàn)程數(shù)(代碼如下)
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
Method[] methods = Job.class.getMethods();
int defaultPoolSize = 3;
int corePoolSize = 0;
if (methods != null && methods.length > 0) {
for (Method method : methods) {
Scheduled annotation = method.getAnnotation(Scheduled.class);
if (annotation != null) {
corePoolSize++;
}
}
if (defaultPoolSize > corePoolSize)
corePoolSize = defaultPoolSize;
}
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
}
}