在SpringBoot中用AOP统计正在执行的定时任务(@Scheduled)


在pom.xml中增加下列依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

AOP类代码如下:

@Aspect
@Component
public class ScheduledAspect {
    private static Logger logger = Logger.getLogger(ScheduledAspect.class);
    
    @Autowired
    private RedisService redisService;

    @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
    public void proxyAspect() {}

    @Around("proxyAspect()")
    public Object doInvoke(ProceedingJoinPoint pjp) throws Throwable {
        // 获取方法名
        String methodName = pjp.getSignature().getName();
        
        // 打印正在执行的方法到控制台
        String redisMember = String.format("%s %s", DateUtil.toDateTimeString(new Date()), methodName);
        System.out.println(redisMember);
        
        // 将方法名+开始时间保存到redis,执行结束后从redis删除
        try {
            redisService.getRedis().sadd("xhs-task", redisMember);
            return pjp.proceed();
        } catch (Exception e) {
            logger.error(methodName, e);
            return null;
        } finally {
            try {
                redisService.getRedis().srem("xhs-task", redisMember);
            } finally {
                RedisService.closeRedis();
            }
        }
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM