示例
1. 获取配置bean
注意使用配置动态刷新注解@RefreshScope.
@Data
@RefreshScope
@Component
@ConfigurationProperties(prefix = "test")
public class TestProperties {
    private String filesPath;
    private String directoryCleanCron;
}2. 实现定时任务的代码
注意:实现定时任务需要使用@EnableScheduling和@Scheduled搭配使用。
@Slf4j
@RefreshScope
@Component
@EnableScheduling
public class FileCleanSchedule implements ApplicationListener<RefreshScopeRefreshedEvent>{
    @Resource
    private TestProperties testProperties;
    @Scheduled(cron = "#{testProperties.getDirectoryCleanCron()}")
    public void clean(){
        log.info("[文件夹清理]-start");
        String filesPath = null;
        try {
            filesPath = testProperties.getFilesPath();
            log.info("[文件夹清理]-需要清理的文件夹路径path:{}", filesPath);
            File file = new File(filesPath);
            log.info("当前执行任务的线程号ID===>{}", Thread.currentThread().getId());
            FileUtil.deleteDirectory(file);
            log.info("[文件夹清理]-end");
        } catch (Exception e) {
            log.error("[文件夹清理]-文件夹{}清理失败,失败信息:{}", filesPath, e.getMessage());
        }
    }
    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
    }
}解决@RefreshScope导致@Scheduled失效的方案,如下:
(1)在定时任务相关类上添加配置动态刷新注解@RefreshScope;
(2)定时任务相关类需要实现应用监听接口ApplicationListener<RefreshScopeRefreshedEvent>,来监听配置刷新。
3. 测试
项目启动后,修改nacos配置,如下:

修改结果:

查看上午11点22分,定时任务执行情况,如下:

问题解决,这里暂时不做原因分析。。。。。


















![【代码随想录】【算法训练营】【第17天】 [110]平衡二叉树 [257]二叉树的所有路径 [404]左叶子之和](https://img-blog.csdnimg.cn/direct/50fab2b67f1a4a44a47f9e4492030359.png)
