您的位置:首页 > 编程语言 > Java开发

Spring Boot 定时任务之多线程

2018-03-05 00:00 579 查看
首先,你需要的注解(关注最后两个注解即可,其他无关):

@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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息