Spring 任务异步和延迟

dan*_*ngc 3 java spring asynchronous task

我需要做一件我不知道的事情,这是最好的做法。

在我向特定服务发送一个请求后,这个请求返回 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

. . .

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

}
Run Code Online (Sandbox Code Playgroud)

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

我怎么能不做一个 Thread.sleep 呢???????

Rub*_*ben 6

可以使用ScheduledExecutorService来安排任务

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

但这不是你想要的。如果服务器在任务调度和执行之间死机怎么办?你会失去你的任务。如果您将消息保存在队列中并稍后检索它,或者使用任何使用持久性的调度程序(a la Quartz)会更好