Multithreading of Spring Boot timing tasks

First, the annotations you need (just pay attention to the last two annotations, nothing else):

@SpringBootApplication
@EnableTransactionManagement
@EnableSwagger2Doc
@EnableCaching
@ComponentScan(basePackages = "cn.xxx")
@EnableAsync
@EnableScheduling
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }

}

And then a configuration class:

@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
        }

    }

}

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

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325235584&siteId=291194637