-
-
Notifications
You must be signed in to change notification settings - Fork 229
feat: add @RecurringTask annotation #725
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
483f824
3f9157a
8d73c51
a0ce185
a90bafb
7fa0f4f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| package com.github.kagkarlsson.scheduler.boot.autoconfigure; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| /** | ||
| * Scheduled tasks are created from the methods that are marked with this annotation. The method | ||
| * must follow these rules: - it must be public - it returns void - it has 0, 1 or 2 inputs with the | ||
| * following types: - {@link com.github.kagkarlsson.scheduler.task.TaskInstance}, generic is ignored | ||
| * and considered Void - {@link com.github.kagkarlsson.scheduler.task.ExecutionContext} | ||
| */ | ||
| @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) | ||
| @Retention(RetentionPolicy.RUNTIME) | ||
| public @interface RecurringTask { | ||
|
|
||
| String name(); | ||
|
|
||
| /* | ||
| The value can be either basic cron or a path to a property | ||
| Examples: | ||
| - ${recurring-sample-task-annotation-no-inputs.cron} | ||
| - 0 * * * * * | ||
| */ | ||
| String cron(); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package com.github.kagkarlsson.scheduler.boot.autoconfigure; | ||
|
|
||
| import javax.sql.DataSource; | ||
| import org.springframework.boot.autoconfigure.AutoConfiguration; | ||
| import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; | ||
| import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.support.GenericApplicationContext; | ||
|
|
||
| @AutoConfiguration(before = DbSchedulerAutoConfiguration.class) | ||
| @ConditionalOnBean(DataSource.class) | ||
| @ConditionalOnProperty(value = "db-scheduler.enabled", matchIfMissing = true) | ||
| public class RecurringTaskAnnotationAutoConfiguration { | ||
|
|
||
| @Bean | ||
| public RecurringTaskRegistryPostProcessor recurringTaskRegistryPostProcessor( | ||
| GenericApplicationContext context) { | ||
| return new RecurringTaskRegistryPostProcessor(context); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| package com.github.kagkarlsson.scheduler.boot.autoconfigure; | ||
|
|
||
| import com.github.kagkarlsson.scheduler.task.ExecutionContext; | ||
| import com.github.kagkarlsson.scheduler.task.Task; | ||
| import com.github.kagkarlsson.scheduler.task.TaskInstance; | ||
| import com.github.kagkarlsson.scheduler.task.helper.Tasks; | ||
| import com.github.kagkarlsson.scheduler.task.schedule.Schedules; | ||
| import java.lang.reflect.InvocationTargetException; | ||
| import java.lang.reflect.Method; | ||
| import java.lang.reflect.Modifier; | ||
| import java.util.Arrays; | ||
| import java.util.Set; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.beans.BeansException; | ||
| import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; | ||
| import org.springframework.beans.factory.support.BeanDefinitionRegistry; | ||
| import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; | ||
| import org.springframework.beans.factory.support.GenericBeanDefinition; | ||
| import org.springframework.context.support.GenericApplicationContext; | ||
| import org.springframework.util.ReflectionUtils; | ||
|
|
||
| /** | ||
| * A {@link BeanDefinitionRegistryPostProcessor} that scans for methods annotated with {@link | ||
| * RecurringTask} and registers them as {@link Task}s in the Spring context. | ||
| * | ||
| * <p>The methods must have a return type of {@code void} and can accept parameters of type {@link | ||
| * TaskInstance}, {@link ExecutionContext}. | ||
| */ | ||
| public class RecurringTaskRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { | ||
|
|
||
| private static final Logger log = | ||
| LoggerFactory.getLogger(RecurringTaskRegistryPostProcessor.class); | ||
|
|
||
| private static final Set<Class<?>> INPUT_ARGUMENTS_AVAILABLE_CLASSES = | ||
| Set.of(TaskInstance.class, ExecutionContext.class); | ||
|
|
||
| private final GenericApplicationContext context; | ||
|
|
||
| public RecurringTaskRegistryPostProcessor(GenericApplicationContext context) { | ||
| this.context = context; | ||
| } | ||
|
|
||
| @Override | ||
| public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) | ||
| throws BeansException { | ||
| String[] beanNames = registry.getBeanDefinitionNames(); | ||
| for (String beanName : beanNames) { | ||
| var beanDef = registry.getBeanDefinition(beanName); | ||
| String beanClassName = beanDef.getBeanClassName(); | ||
| if (beanClassName == null) { | ||
| continue; | ||
| } | ||
| try { | ||
| Class<?> beanClass = Class.forName(beanClassName); | ||
| ReflectionUtils.doWithMethods( | ||
| beanClass, | ||
| method -> { | ||
| RecurringTask recurringTask = method.getAnnotation(RecurringTask.class); | ||
| if (recurringTask != null) { | ||
| validateMethod(method); | ||
| GenericBeanDefinition taskDef = | ||
| buildTaskBeanDefinition(recurringTask, method, beanName); | ||
| registry.registerBeanDefinition(recurringTask.name(), taskDef); | ||
| } | ||
| }, | ||
| method -> method.isAnnotationPresent(RecurringTask.class)); | ||
| } catch (ClassNotFoundException ignored) { | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private GenericBeanDefinition buildTaskBeanDefinition( | ||
| RecurringTask recurringTask, Method method, String beanName) { | ||
| GenericBeanDefinition taskDef = new GenericBeanDefinition(); | ||
| taskDef.setBeanClass(Task.class); | ||
| taskDef.setInstanceSupplier( | ||
| () -> { | ||
| String resolvedCron = resolveCron(recurringTask.cron()); | ||
| log.info( | ||
| "Creating a task from @RecurringTask with name={} and cron={}", | ||
| recurringTask.name(), | ||
| resolvedCron); | ||
| return createTaskFromMethod( | ||
| recurringTask, method, context.getBean(beanName), resolvedCron); | ||
| }); | ||
| return taskDef; | ||
| } | ||
|
|
||
| private String resolveCron(String rawCron) { | ||
| if (rawCron.startsWith("$")) { | ||
| return context.getEnvironment().resolveRequiredPlaceholders(rawCron); | ||
| } else { | ||
| return rawCron; | ||
| } | ||
| } | ||
|
|
||
| private void validateMethod(Method method) { | ||
| if (!Modifier.isPublic(method.getModifiers())) { | ||
| throw new IllegalArgumentException( | ||
| "RecurringTask annotated method must be public, see the annotation javadoc"); | ||
| } | ||
| if (!method.getReturnType().equals(Void.TYPE)) { | ||
| throw new IllegalArgumentException( | ||
| "RecurringTask annotated method must have return type Void, see the annotation javadoc"); | ||
| } | ||
|
|
||
| if (method.getParameterCount() != 0) { | ||
| for (Class<?> parameterType : method.getParameterTypes()) { | ||
| if (!INPUT_ARGUMENTS_AVAILABLE_CLASSES.contains(parameterType)) { | ||
| throw new IllegalArgumentException( | ||
| "RecurringTask annotated method is required to have specific inputs: " | ||
| + INPUT_ARGUMENTS_AVAILABLE_CLASSES); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private Task<?> createTaskFromMethod( | ||
| RecurringTask recurringTask, Method method, Object existingObject, String resolvedCron) { | ||
|
|
||
| return Tasks.recurring(recurringTask.name(), Schedules.cron(resolvedCron)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I miss the option to configure the FailureHandler. As far as I can see, the FailureHandler behavior cannot be configured. This means that the default Failure Handler is used automatically, which is not suitable for everyone. I would be grateful if this functionality could be taken into account in this pull request.
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Default is Do you need a completely custom implementation? (I.e. lookup a FailureHandler in the app-context based on a bean-name?)
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes. I think that would be useful feature. You define your FailureHandlerBean. This FailureHandler will then be used for all the task, which are created via @RecurringTask annotation. But this will not be enough for the case, where you have multiple @RecurringTask where each of them need an different FailureHandler.
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am also ok with adding customizable failure-handler in a future iteration of this. This is a convenient short-hand for most common recurring tasks, and I don't think it needs to cover all variants |
||
| .execute( | ||
| (instance, ctx) -> { | ||
| Object[] inputs = | ||
| Arrays.stream(method.getParameterTypes()) | ||
| .map( | ||
| paramType -> { | ||
| if (paramType.equals(TaskInstance.class)) { | ||
| return instance; | ||
| } else if (paramType.equals(ExecutionContext.class)) { | ||
| return ctx; | ||
| } | ||
| throw new IllegalArgumentException( | ||
| "RecurringTask annotated method is required to have specific inputs: " | ||
| + INPUT_ARGUMENTS_AVAILABLE_CLASSES); | ||
| }) | ||
| .toArray(); | ||
| try { | ||
| method.invoke(existingObject, inputs); | ||
| } catch (IllegalAccessException | InvocationTargetException e) { | ||
| throw new RuntimeException( | ||
| "An error happened while calling a task method through reflection, method name: " | ||
| + method.getName(), | ||
| e); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| @Override | ||
| public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) | ||
| throws BeansException { | ||
| // No-op | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerAutoConfiguration,\ | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerMetricsAutoConfiguration,\ | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerActuatorAutoConfiguration | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerActuatorAutoConfiguration,\ | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.RecurringTaskAnnotationAutoConfiguration |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerAutoConfiguration | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerMetricsAutoConfiguration | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerActuatorAutoConfiguration | ||
| com.github.kagkarlsson.scheduler.boot.autoconfigure.RecurringTaskAnnotationAutoConfiguration |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it be possible to have the
RecurringTaskRegistryPostProcessorresolve property-references in the cron-pattern?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea! I did a quick test and it's possible to make, needs some enhancements of
RecurringTaskRegistryPostProcessor.I'll add this to the PR.