I have several scheduled jobs in Spring Boot that are defined using @Scheduled(…). I am using these scheduled jobs to test APIs. I have a ugly solution that allows me to turn enable/disable these scheduled jobs, but I was wondering if there was a more elegant solution. From my searching, I couldn't find a up-to-date, relevant solution.
Here is basically what I am working with:
@RestController
@RequestMapping("something")
public class MyController {
...
@GetMapping("/map1")
public ResponseEntity<Object> service1(...) { ... }
@GetMapping("/map2")
public ResponseEntity<Object> service2(...) { ... }
}
I have all the scheduled jobs located in a central location. I have implement two ways to control their execution: switch to enable/disable all scheduled tasks and one to enable/disable individual scheduled jobs.
@Component
@ConditionalOnProperty(value="jobs.status.all")
public class ScheduledJobs {
@Autowired
MyController mc;
@Autowired
Environment env;
@Scheduled(...)
public void job1() {
if(Boolean.parseBoolean(env.getProperty("jobs.status.one", "false")) {
mc.service1();
}
}
@Scheduled(...)
public void job2() {
if(Boolean.parseBoolean(env.getProperty("jobs.status.two", "false") {
mc.service2();
}
}
}
This allows me to controls scheduled jobs from a properties file(all or individual ones). My intention is remove the execution of job1()
and job2()
because that is ugly and inefficient.
What would be a more elegant solution to enable and disable scheduled jobs?
EDIT: I was looking for a more elegant solution of enabling/disabling individually scheduled jobs. In case where I would want to enable some jobs while disabling others.