'Avoiding using Thread.sleep() when working with SqsListener
I have SQS listener, and under a certain condition, I need to wait 120 seconds before executing method1(). But as I know SQS listener works multithreaded. Is there a way to avoid using Thread.sleep() to reuse the thread rather than leave it waiting? Here is listener code:
@SqsListener(value = "${test}", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void listenTransactionEvent(@Payload SQSEvent sqsEvent) {
String sqsPlainMessage = sqsEvent.getMessage();
if (sqsPlainMessage.equals("test")) {
Thread.sleep(120 * 1000L);
method1();
} else {
method2();
}
}
and configuration:
@Bean
public QueueMessageHandlerFactory queueMessageHandlerFactory(
final ObjectMapper mapper,
final AmazonSQSAsync amazonSQSAsync
) {
final QueueMessageHandlerFactory queueHandlerFactory = new QueueMessageHandlerFactory();
queueHandlerFactory.setAmazonSqs(amazonSQSAsync);
queueHandlerFactory.setArgumentResolvers(Collections.singletonList(
new PayloadMethodArgumentResolver(jackson2MessageConverter(mapper))
));
return queueHandlerFactory;
}
Solution 1:[1]
I believe you may be looking for java.util.Timer to schedule a TimeTask or even using a java.util.concurrent.Future could release the thread calling listenTransactionEvent, but the waiting will just change place, sometimes depending on context Thread.sleep might be an acceptable solution.
Best regards.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | João |
