Spring-boot @Async没有运行@Scheduled

时间:2016-02-04 08:28:52

标签: java spring spring-boot spring-scheduled spring-async

我使用this tutorialit's github project作为此SSCCE的基础。

由于未知原因,标记为@Async的方法从@Scheduled方法运行,始终同步执行。

我正在寻找修复或解决方法,以使performTask()中的代码运行异常。

以下课程:

Application.java

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class Application implements AsyncConfigurer{

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }

    @Override
    @Bean(name="asyncExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
        exec.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*2);
        exec.setThreadGroupName("MyCustomExecutor");
        exec.setWaitForTasksToCompleteOnShutdown(true);
        exec.setBeanName("asyncExecutor");
        exec.initialize();
        return exec;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

MyAsyncService.java

@Service
public class MyAsyncService {

    static AtomicInteger taskNoCounter = new AtomicInteger();

    public MyAsyncService() {
    }

    @Async("asyncExecutor")
    public void performTask() {
        int delayMs = (int) (System.currentTimeMillis()%1000+1000);
        int taskNo = taskNoCounter.incrementAndGet();
        String taskInfo = "MyAsyncTask [taskNo=" + taskNo + ", delayMs=" + delayMs + ", threadId="+Thread.currentThread().getId()+"]";
        System.out.println("+ start " +taskInfo);
        try {
            Thread.sleep(delayMs);
        } catch (InterruptedException e) {
            // empty on purpose
        }
        System.out.println("- end   " +taskInfo);
    }

}

ScheduledTasks.java

@Component
public class ScheduledTasks {

    @Autowired
    MyAsyncService service;

    @Scheduled(fixedRate = 1000)
    public void reportCurrentTime() {
        for (int i=0; i<20; i++) {
            service.performTask();
        }

    }
}

产生以下同步结果:

+ start MyAsyncTask [taskNo=1, delayMs=1874, threadId=16]
- end   MyAsyncTask [taskNo=1, delayMs=1874, threadId=16]
+ start MyAsyncTask [taskNo=2, delayMs=1749, threadId=16]
- end   MyAsyncTask [taskNo=2, delayMs=1749, threadId=16]
+ start MyAsyncTask [taskNo=3, delayMs=1498, threadId=16]
- end   MyAsyncTask [taskNo=3, delayMs=1498, threadId=16]
+ start MyAsyncTask [taskNo=4, delayMs=1997, threadId=16]
- end   MyAsyncTask [taskNo=4, delayMs=1997, threadId=16]
+ start MyAsyncTask [taskNo=5, delayMs=1994, threadId=16]

1 个答案:

答案 0 :(得分:0)

问题是没有设置<div class="bottom-container">HERE ALL CONTENT</div> 的{​​{1}}属性。

默认情况下,corePoolSizeThreadPoolTaskExecutor,并且仅当队列已满时线程数才会增加。由于我的队列是无限的,因此池中没有创建额外的线程。

我最终做了:

corePoolSize