-
-
Notifications
You must be signed in to change notification settings - Fork 222
Description
In my Spring Boot project I have tasks that are classes inheriting from a shared BaseTask
class. One of these tasks may be either run just once or run on a schedule and so I want my BaseTask
to be able to handle both (instead of having to create separate tasks that inherit from RecurringTask
or OneTimeTask
).
Additionally, I want to register a recurring instance of this task to run on startup using the @Bean
annotation provided by the Spring Boot starter. However, for the scheduler to register this recurring task on startup the task needs an onStartup
implementation. Looking at the implementation in RecurringTask
I see that there is a ScheduleRecurringOnStartup
helper class with a lot of logic that I would not want to implement and maintain myself. Why isn't this class public but only exposed through RecurringTask
?
I realize that there are two possible workarounds: Inherit from RecurringTask
or use Tasks.recurring
. None of these map very cleanly to what I'm trying to achieve: I want my task to be able to work as both a OneTimeTask and a RecurringTask, and I don't want my task implementations to live in a lambda.
An approximation of my ideal setup:
class BaseTask(schedule: Schedule? = null) : AbstractTask(...), OnStartup {
override fun onStartup(...) {
if (schedule = null) return
// Or instantiate in constructor. Could include handling for onStartup with non-recurring tasks.
ScheduleRecurringOnStartup("recurring", null, schedule).apply(...)
}
}
class Mytask(...) : BaseTask(...) {}
@Bean
fun myRecurringTask() = MyTask(Schedules.cron("*/10 * * * * ?"))
@Bean
fun myOneTimeTask() = MyTask() // Not run on startup, but is registered in scheduler
I suggest making these helpers public to be able to mimic OneTimeTask
and RecurringTask
cleanly with a class-based approach without having to (re-)implement advanced scheduling logic.