2016-12-01 79 views
1

我需要做的是onething我不知道至极就是对此最好的做法。春任务异步和延迟

在我向特定服务发送一个请求后,这个返回OK并排队我的请求。我有一个回调服务,用于通知何时结束。

问题是,整个过程可能需要很长时间而不通知任何事情,之后我需要考虑超时。

该应用程序是SpringBoot APP,我正考虑在带睡眠时间的服务方法上使用注释@EnableAsync和@Async。

@Configuration 
@EnableAsync 
public class AsyncConfiguration implements AsyncConfigurer { 

    @Override 
    public Executor getAsyncExecutor() { 

     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); 
     executor.setCorePoolSize(2); 
     executor.setMaxPoolSize(10); 
     executor.setQueueCapacity(500); 
     executor.setThreadNamePrefix("TIMCLL-"); 
     executor.initialize(); 
     return executor; 

    } 

    @Override 
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { 
     // TODO Auto-generated method stub 
     return null; 
    } 

} 

。 。 。

@Async 
public void verifyStatusTimPayment() throws InterruptedException { 

    Thread.sleep(5000); 
    logger.info("Executed after 5s " + new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date())); 

} 

验证需要在请求后15分钟完成,并且每个请求只发生一次。

我怎么能做到这一点,而不做出了Thread.sleep ?????

回答

1

可以使用ScheduledExecutorService安排任务

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 
... 
scheduler.schedule(() -> {yourtaskhere}, 15, TimeUnit.MINUTES); 

这是不是你想要的。如果服务器在任务调度和执行之间死亡会怎么样?你会失去你的任务。 如果您将消息保存在队列中并在稍后检索,或使用任何使用余辉的调度程序(a Quartz)