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?
CodePudding user response:
Please note the simple rules that we need to follow to annotate a method with @Scheduled
are:
- the method should typically have a void return type (if not, the returned value will be ignored)
- the method should not expect any parameters
Solution 1. Create two separate methods
Keep it simple:
public class DataService implements Service {
public String getData() {
return "Data";
}
@Scheduled(cron = "0 0 8 * * ?")
public void performScheduler() {
/*scheduler logic*/
String data = getData();
/* process data */
}
}
Solution 2. Create separate service for scheduler
public class SchedulerDataService {
private Service service;
public SchedulerDataService(Service service) {
this.service = service;
}
@Scheduled(cron = "0 0 8 * * ?")
public void performScheduler() {
/*scheduler logic*/
String data = service.getData();
/* process data */
}
}
CodePudding user response:
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"); }