我有一个Sping Boot 应用程序,我需要公开2个端点以启动和停止计划任务。cron/fixed delay表达式在数据库中定义。此配置是针对每个客户端的。例如,如果客户端A调用启动API,我需要根据数据库中为该客户端A定义的配置启动计划任务。对于所有客户端,任务内部的逻辑都是相同的。我的问题是,任何客户端都可以调用启动和停止API,那么如何在调用启动API时动态启动任务,以及在客户端调用停止API时停止任务(仅特定客户端的任务,而不是所有任务` @RestController
class SchedulerController {
@Autowired
TaskScheduler taskScheduler;
ScheduledFuture scheduledFuture;
@RequestMapping("start")
ResponseEntity start(@RequestParam String clientId) {
String fixedDelay = "get it from database for the provided client";
scheduledFuture = taskScheduler.schedule(excuteLogic(clientId), fixedDelay);
// generate a task id and save in db against clientid
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping("stop")
ResponseEntity stop(@RequestParam String clientId) {
// get the taskid from database for the clientId
// stop the task
return new ResponseEntity(HttpStatus.OK);
}
private Runnable excuteLogic(String clientId) {
return () -> {
// logic goes here
};
}
}计划生成任务ID并根据clientid将其保存在数据库中,但不确定如何停止为提供的客户端计划的特定任务。
|