'Get list of all Scheduled crons

I have a springframework boot application, on that I have a lot of scheduled cron, now I'm creating a rest controller(GET) in which I want to get the list(metadata) of all schedule crons on my project

SchedulerApplication.java

@SpringBootApplication
@EnableScheduling
@EnableAutoConfiguration
public class SchedulerApplication {
  public static void main(String[] args) {
    SpringApplication.run(SchedulerApplication.class, args);
  }

Class1.java

@Scheduled(cron = "${doSomething1}")
  public void execute() {
    ....
  }

Class2.java

@Scheduled(cron = "${doSomething2}")
  public void execute() {
    ....
  }

application.yml

doSomething1: 0 45 2 * * ? 
doSomething2: 0 5 9 ? * * 

and this is my rest controller


@Controller
@RequestMapping(value = "api/v1/scheduler")
public class SchedulerController {

  @Autowired
  private SchedulerService schedulerService;

  @RequestMapping(value = "/crons", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
  public ResponseBody getAllAvailableCrons() {
    return schedulerService.getAllAvailableCrons();
  }

}
@Service
public class SchedulerService {

  public ResponseBody getAllAvailableCrons() {
    
  }
}



Solution 1:[1]

You can use @ConfigurationProperties to fetch them from application.yml and autowire them in the Service (using a prefix would make it a bit cleaner):

application.yml

crons:
   doSomething1: 0 45 2 * * ? 
   doSomething2: 0 5 9 ? * * 

ConfigurationProperties:

@ConfigurationProperties(prefix = "crons") 
public class CronProperties { 

private Map<String,String>> crons;  
    // standard getters and setters 
}

Service:

@Service
public class SchedulerService {

@Autowired
private CronProperties cronProperties

public ResponseBody getAllAvailableCrons() {
    // use cronProperties.getCrons()
}

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 str8tonowhere