kagkarlsson / db-scheduler

Persistent cluster-friendly scheduler for Java
Apache License 2.0
1.22k stars 186 forks source link

Feature: Support Spring @Scheduled annotation as a way of instantiating Recurring tasks #509

Open kagkarlsson opened 2 months ago

kagkarlsson commented 2 months ago

Support Spring @Scheduled annotation as a way of instantiating Recurring tasks. Makes for a convenient and compact way to define recurring tasks

iluwa commented 1 month ago

I like the idea! Potentially it'd reduce a big portion of boilerplate. I'd like to work on the feature

kagkarlsson commented 1 month ago

Feel free to do so! The help is appreciated!

I haven't looked at how the integration works, or if there are any potential pitfalls for db-scheduler, so that is part of the job 😄

kagkarlsson commented 1 month ago

If it turns out that it is not possible to hook into Spring's @Scheduled annotation, then we can consider creating our own custom annotation, e.g @RecurringTask(name="my-task", cron="...")

iluwa commented 1 month ago

Thank you for looking into this. I'm curious, is it because that the db-scheduler can't implement "fixed-interval" stuff from this annotation (like fixedRate, fixedDelay)?

Initially I was planning to put the feature into spring-boot-module. But since it's not limited by spring anymore, the core package looks like a more suitable place.

kagkarlsson commented 1 month ago

fixedRate might be difficult. It is possible to create a Schedule supporting it but may have quirks (when execution-duration > fixedRate).

It may be that we need to get a class-instance containing the annotated method from something like the spring context, since it may have dependencies and such. In that case it will have to reside in the spring-boot-module. Not sure exactly how it would look if put in core.. 🤔

kamko commented 1 day ago

I was exploring how to implement an annotation to serve as a more or less drop-in replacement for Spring's Scheduled cron jobs.

fixedRate might be difficult. It is possible to create a schedule supporting it, but it may have quirks (e.g., when execution duration exceeds fixedRate).

I also think the polling strategy might pose some challenges. The biggest issue, however, would be that having db-scheduler hook onto the Scheduled annotation would require disabling Spring's annotation-driven scheduling. If we cannot achieve a 100% drop-in replacement, it might be better to create our own annotation.

I'm not sure how the annotation could work without Spring. Where would we get the actual class instances to run the methods? I don't think that having annotation without any actual way to use it is sufficient.

I have experimented with this, and by using BeanDefinitionRegistryPostProcessor, you can scan for beans with annotated methods and dynamically create recurring tasks, which would be injected with Spring dependencies.