i have a get function in my microservice which essentially fetchs data from a database. this function is running as a scheduler (cron job) and also as an api end point which can be triggered from the UI.
@GetMapping(value = "getDataUI") public String getDataUI() throws Exception { return service.getData(); // call to service layer }
//service layer @Scheduled(cron = "0 0 8 * * ?") public String getData(){ // logic here // }
i want to add some logic inside getData() which will only be executed when it is being triggered by the scheduler and the logic should be skipped when being called from the UI (“/getDataUI”).
how can i do this? or is there a better way to implement what i am trying to do?
Advertisement
Answer
This can be achieve by following way
- Refactoring of cron job and service method
- Cron Job can have wrapper method to call Service method.
- Add parameter in service method
In above example:
1.Same as above for getDataUI
@GetMapping(value = "getDataUI") public String getDataUI() throws Exception { -- return service.getData("UI"); // call to service layer }
Removed schedule annotation from Service layer
//service layer
public String getData(String param){ if(param=="CRON") // else // }
Schedule Task
@Scheduled(cron = "0 0 8 * * ?") public String getScheduleData(){ //service.getData("CRON"); }