Issue
I want to run a job based on the cron expression, but it should look for the cron expression from the DB after a rest call.
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Controller
**************
@PostMapping
@RequestMapping(value = "/addProduct")
public ResponseEntity saveProduct(@RequestBody Product product){
prodList.add(product);
startJob();
return new ResponseEntity("Product saved successfully", HttpStatus.OK);
}
@Scheduled(cron = "*/2 * * * * *")
public void startJob() {
System.out.println("printing"+ new Date());
}
Once the REST API will be hit, it should wait for the cron expression, which we can get from the database or from any method, then it should start at the specified time.
It is working like a normal method call.
Solution
You can make your controller to implement SchedulingConfigurer
which has a callback called configureTasks()
which will be invoked when Spring starts up.
In this callback , you can access the ScheduledTaskRegistrar
which is a helper bean that can used to programatically schedule a task. So , save this helper bean into the controller 's internal field such that your controller can access it to schedule a new task later .
@RestController
public class MyController implements SchedulingConfigurer{
private ScheduledTaskRegistrar scheduledTaskRegistrar;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
this.scheduledTaskRegistrar = taskRegistrar;
}
@PostMapping
@RequestMapping(value = "/addProduct")
public ResponseEntity saveProduct(@RequestBody Product product){
//.....
//Load the cron expression from database
String cronExpression = loadCronExpressionFromDatabase();
CronTask cronTask = new CronTask(() -> startJob() ,cronExpression);
scheduledTaskRegistrar.scheduleCronTask(cronTask);
return new ResponseEntity("Product saved successfully", HttpStatus.OK);
}
public void startJob() {
System.out.println("printing"+ new Date());
}
}
Answered By - Ken Chan Answer Checked By - David Goodson (WPSolving Volunteer)