Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ For Spring Boot applications, there is a starter `db-scheduler-spring-boot-start
```
**NOTE**: This includes the db-scheduler dependency itself.
2. In your configuration, expose your `Task`'s as Spring beans. If they are recurring, they will automatically be picked up and started.
Alternative option for creating recurring tasks is to use `@RecurringTask` annotation ([see examples](./examples/spring-boot-example/src/main/java/com/github/kagkarlsson/examples/boot/config/BasicExamplesConfiguration.java)). In this case the task is created and registered in Spring context.
3. If you want to expose `Scheduler` state into actuator health information you need to enable `db-scheduler` health indicator. [Spring Health Information.](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-health)
4. Run the app.

Expand Down
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);
}
Comment on lines +15 to +19
Copy link
Owner

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 RecurringTaskRegistryPostProcessor resolve property-references in the cron-pattern?

Copy link
Contributor Author

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.

}
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))
Copy link
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default is

this.onFailure = new FailureHandler.OnFailureReschedule<>(schedule);

Do you need a completely custom implementation? (I.e. lookup a FailureHandler in the app-context based on a bean-name?)

Copy link
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Owner

Choose a reason for hiding this comment

The 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
Loading
Loading