springaopaspectjspring-aopspring-scheduled

Spring AOP - Determine whether method was invoked by @Scheduled


I have a runtime annotation @MyAnnotation, and I would like to write an Aspect that determines whether the test() method below was called by:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Scheduled(cron = "*/1 * * * * *") // scheduled to invoke every second
    @MyAnnotation
    public void test() {
        // business logic
    }
}

aspect code (pointcut + advice)

    @Around(value="@annotation(myAnnotation)")
    public Object featureToggle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) throws Throwable {
        Boolean isInvoked = // TODO - is invoked by @Scheduled or not
    }

Solution

  • you can set the scheudle thread name prefix, then determine it by thread name.

    spring
      task:
        scheduling:
          thread-name-prefix: xxxx-scheduling-
    
    @Aspect
    @Component
    @RequiredArgsConstructor
    public class ScheduledTaskAspect {
        private final TaskSchedulingProperties taskSchedulingProperties;
    
        @Around(value="@annotation(myAnnotation)")
        public Object featureToggle(ProceedingJoinPoint joinPoint, MyAnnotation myAnnotation) throws Throwable {
            String currentThreadName = Thread.currentThread().getName();
            Boolean isInvoked = currentThreadName.startsWith(taskSchedulingProperties.getThreadNamePrefix());
        }
    }