Spring Task Async and Delayed

2019-07-21 20:29发布

I need to do onething that I don't know wich is the best practice to this.

After I send one request to an especific service, this one returns OK and queue my request. I have a callback service that is used to notify when it ends.

The problem is that the whole process can take a long time and over without notify anything and after that I need to consider a timeout.

The application is SpringBoot APP and I was considering to use the annotations @EnableAsync and @Async on a service method with a Sleep time.

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

}

The verification needs to be done 15 minutes after the request and have to occur just one time per request.

How can I do this without make a Thread.sleep ?????

2条回答
Emotional °昔
2楼-- · 2019-07-21 21:10

i think we can use @Scheduled in latest spring. it will run every 15 minutes like method is annotated as below

@Scheduled(cron = "0 0/15 * * * *")
public void verifyStatusTimPayment() throws InterruptedException {
    logger.info( "Executed after 5s " +  new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(new Date())); 

}

i know i am late but might help someone who is going through thread

查看更多
不美不萌又怎样
3楼-- · 2019-07-21 21:30

You could use the ScheduledExecutorService to schedule the Task

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

But this is not what you want. What if the server dies between the scheduling of the task and its execution? you will lose your task. It would be better if you persist the message in a queue, and retrieve it later, or use any scheduler that uses persistence (a la Quartz)

查看更多
登录 后发表回答