1

I would like allow users to make periodic orders in an Ecommerce application, for example every week, every two weeks. I used the @Scheduled annotation, however, the annotated function cannot take arguments or have a return value.

Are there are any other alternatives or solutions to this issue?

@PostMapping(value="/period")
@Scheduled(fixedRate = 20000)
public ResponseEntity<Long> insertPeriodic(@Valid @RequestBody NewOrderDTO newOrderDTO){
    Order order = orderService.insert(newOrderDTO);
    URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(order.getId()).toUri();
    return ResponseEntity.created(uri).body(order.getId());
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Mehdi.K
  • 21
  • 3
  • Does this answer your question? [Scheduling a job with Spring programmatically (with fixedRate set dynamically)](https://stackoverflow.com/questions/14630539/scheduling-a-job-with-spring-programmatically-with-fixedrate-set-dynamically) – João Dias Jan 06 '22 at 22:25
  • 2
    Does this approach scale with a lot of orders ? What if we have, let's say 10 000 periodic orders, wouldn't the overhead for creating a task for each order be too big ? – Odess4 Jan 06 '22 at 22:28

1 Answers1

2

What do you mean by "allow users to make periodic orders"? In my understanding what you would like to achieve is that the user can submit an order, which is periodically executed (for example in every 2 weeks). This is not the same!

You cannot use @Scheduled annotation on a REST endpoint. Consider changing your architecture. Allow the user to save a periodic order on a REST endpoint:

@PostMapping(value="/periodic-order")
public ResponseEntity<Long> insertPeriodic(@Valid @RequestBody NewPeriodicOrderDTO newOrderDTO){
    // calling service layer, which persists this order to database 
}

Then create a scheduler service, which is annotated by @Scheduled and executes the order-related logic what you desire, somewhat like this:

@Service
public class ScheduledOrderExecutorService {

    private final OrderService orderService;

    public ScheduledOrderExecutorService(OrderService orderService) {
        this.orderService = orderService;
    }

    @Scheduled(fixedRate = 20000)
    public void executePeriodicOrder() {
        // retrieveing corresponding orders via orderService, and implementing related business logic
    }

}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Isakots
  • 94
  • 3