通过反射获取Spring定时器@Scheduled注解中fixedDelay时间

前言:

如何获取Spring的定时器注解@Scheduled中的时间值(即获取3000):@Scheduled(fixedDelay = 3000)

注:定时器类:org.springframework.scheduling.annotation.Scheduled

1.定时任务类

public class AlarmTask {
    @Scheduled(fixedDelay = 3000) 
    public void alarm() {
    //定时任务
    }
}

2.获取方法

/**
     * 根据方法名,获定时器注解内的延时时间值
     * 
     * @param clasz
     *            用到定时器的类(AlarmTask)
     * @param methodName
     *            注释下的方法名(如:"alarm")
     */
    private long getFixedDelayValueByMethodName(Class clasz, String methodName) {
        long fixedDelay = 1;
        Method method;
        try {
            method = AlarmPushTask.class.getDeclaredMethod(methodName, null);
            Annotation[] annotations = method.getAnnotations();
            Annotation annotation = annotations[0];
            Scheduled scheduled = (Scheduled) annotation;
            fixedDelay = scheduled.fixedDelay();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return fixedDelay;
    }

注:获取Scheduled注解接口中的其他属性值(fixedRate,fixedDelay,cron等),只需修改scheduled.fixedDelay(),即可获取其他字段的值。

3.用法:

void test() {
        getFixedDelayValueByMethodName(AlarmTask.class,"alarm");
    }

猜你喜欢

转载自blog.csdn.net/x541211190/article/details/80139248