Spring Boot 定时任务之多线程
程序员文章站
2022-05-01 16:31:01
...
首先,你需要的注解(关注最后两个注解即可,其他无关):
@SpringBootApplication
@EnableTransactionManagement
@EnableSwagger2Doc
@EnableCaching
@ComponentScan(basePackages = "cn.xxx")
@EnableAsync
@EnableScheduling
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
然后是一个配置类:
@Configuration
public class TaskExcutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setCorePoolSize(5);
threadPoolTaskExecutor.setMaxPoolSize(100);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new MyAsyncExceptionHandler();
}
class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
//do something
}
}
}
然后是一个Task:
@Component
public class WorTask {
@Autowired
private RedisTemplate redisTemplate;
/**
* 每3秒运行一次
*/
@Scheduled(fixedDelay = 3000)
@Async
public void spiderWordsByUrlFromRedis() {
System.out.println("Test");
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
转载于:https://my.oschina.net/vright/blog/1630082