用法:
开启任务调度:@EnableScheduling
定义一个类,把这个类加入到容器中,在方法上加
@Scheduled(cron = "百度表达式即可")
复杂的任务: 1,默认的线程池大小是1,可以在配置文件中配置task
2,async
3,手写线程池+从spring中获取线程池单例
示例:
普通类从容器中取对象取出线程池,单例线程池和执行线程
package com.sm.qy28.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringConfigUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static <T> T getBean(Class<T> clazz) {
return (T) applicationContext.getBean(clazz);
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringConfigUtils.applicationContext = applicationContext;
}
}
package com.sm.qy28.common.async;
import com.sm.qy28.common.utils.SpringConfigUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.swing.*;
public class AsyncManager {
private static ThreadPoolTaskExecutor threadPoolTaskExecutor;
private static AsyncManager asyncManager;
private AsyncManager() {
threadPoolTaskExecutor= SpringConfigUtils.getBean(ThreadPoolTaskExecutor.class);
}
public static AsyncManager getInstance(){
if(asyncManager==null){
return asyncManager= new AsyncManager();
}
return asyncManager;
}
public void execute(Runnable runnable){
threadPoolTaskExecutor.execute(runnable);
}
}
package com.sm.qy28.common.async;
public class AsyncFactory {
public static Runnable xxxx(){
Runnable runnable=()->{
};
return runnable;
}
}
springboot配置文件中配置线程池的线程
spring.task.execution.pool.core-size=50