Am Unable to fetch value from DB for a cron expression and use it in @Scheduled annotation to run my Scheduler
my project is spring boot reactive with Postgres db
am using jdk17 spring-boot-starter-parent 3.1.4 Postgres version "PostgreSQL 16.0 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0, 64-bit"
@Component
public class MyScheduler {
private final myCronExpressionFetcherFetcherServiceImpl myCronExpressionFetcherService;
@Scheduled(cron = "#{@myCronExpressionFetcherService.getCronExpression()}")
public void checkAndProcessInProgressAppointments() {
TaskSchedulerConfig taskSchedulerConfig = myCronExpressionFetcherRepo.findByTaskName("PENDING_TASKS_SCHEDULER").block();
// my task
}
}
@Repository
public interface MyCronExpressionFetcherRepo extends ReactiveCrudRepository<TaskSchedulerConfig, Long> {
Mono<TaskSchedulerConfig> findByTaskName(String taskName);
}
@Table(name = TABLE_MY_SCHDULER_CONFIG)
@Data
@Builder
public class TaskSchedulerConfig {
@Id
private Long id;
private String taskName;
private String cronExpression;
private boolean enabled;
}
@Service
public class MyCronExpressionFetcherFetcherServiceImpl {
private final MyCronExpressionFetcherRepo tasCronExpressionFetcherRepo;
public Mono<String> getCronExpression() {
log.info("Fetching cron expression for task: {}", PENDING_TASKS_SCHEDULER);
return tasCronExpressionFetcherRepo.findByTaskName(PENDING_TASKS_SCHEDULER)
.map(taskSchedulerConfig -> {
if (taskSchedulerConfig != null) {
log.info("Fetched cron expression: {}", taskSchedulerConfig.getCronExpression());
return taskSchedulerConfig.getCronExpression();
} else {
log.info("TaskSchedulerConfig not found. Using default cron expression.");
return "";
}
});
}
i felt like SpeL with reactive in combination of @Scheduled is not working. i am getting error like Unable to evaluate expression and a Bean is not found for my Impl class but my Impl class is with @Service annotation.
Comment From: snicoll
i felt like SpeL with reactive in combination of @scheduled is not working.
Invoking a reactive method with SpEL is not supported indeed. You are conflating two different models here. The cron expression is retrieved on startup, the reactive pipeline is not ready yet. A database call also means that you're making the whole data layer dependent on that particular bean.
i am getting error like Unable to evaluate expression and a Bean is not found for my Impl class but my Impl class is with @service annotation.
Going forward, please take some time to make the report more actionable. Rather than pasting code in text and not providing the actual exception,share a small sample we can run ourselves in the form of a zip attached to the issue or a link to a GitHub repository.