You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何实现每5分钟定时检查HDFS路径存在并下载对应文件

HDFS定时校验下载的定时调度实现方案

首先先修正现有download方法的逻辑问题:当前代码无论路径校验结果是否为true,都会执行下载操作,需要补充判断逻辑:

public void download(final String hdfs, final Path outputPath)
{
    final org.apache.hadoop.fs.Path hdfsAbsolutePath = getHdfsFile(hdfsLocalPath).getPath();
    logger.info("path check {}", hdfsAbsolutePath.getName());
    final boolean isPathExist =  checkPathExistance(hdfsAbsolutePath);
    // 仅路径存在时执行下载
    if (isPathExist) {
        downloadFromHDFS(hdfsAbsolutePath, outputPath);
        // 若只需下载一次,可在此处添加停止调度的逻辑
    }
}

方案1:JDK自带ScheduledExecutorService实现(无额外依赖)

直接用JDK自带的定时线程池实现5分钟间隔调度,代码示例如下:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

// 初始化定时调度线程池,单线程即可满足需求
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

/**
 * 启动HDFS路径校验定时任务
 * @param hdfsPath 待校验的HDFS路径
 * @param localOutputPath 本地下载输出路径
 */
public void startScheduleTask(String hdfsPath, Path localOutputPath) {
    // 参数说明:执行的任务、首次启动延迟、间隔周期、时间单位
    // 此处配置为启动后立即执行第一次校验,之后每5分钟执行一次
    scheduler.scheduleAtFixedRate(
        () -> download(hdfsPath, localOutputPath),
        0,
        5,
        TimeUnit.MINUTES
    );
}

// 应用关闭时调用,销毁线程池避免资源泄露
public void stopScheduleTask() {
    if (!scheduler.isShutdown()) {
        scheduler.shutdown();
        try {
            if (!scheduler.awaitTermination(1, TimeUnit.MINUTES)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

方案2:Spring框架原生@Scheduled注解实现

如果项目基于Spring/SpringBoot开发,可直接用框架自带的定时调度能力,代码更简洁:

  1. 在项目启动类上添加@EnableScheduling注解开启定时调度能力
  2. 编写定时任务方法:
import org.springframework.scheduling.annotation.Scheduled;

// 300000毫秒 = 5分钟,fixedRate表示上一次执行开始时间后间隔5分钟执行下一次
@Scheduled(fixedRate = 300000)
public void hdfsCheckTask() {
    // 替换为实际的HDFS路径和本地输出路径
    download("hdfs://your-namespace/your-target-path", Path.of("/your/local/output/path"));
}

优化建议

  • 建议复用FileSystem实例,不要每次调用checkPathExistance都新建连接,降低HDFS集群的连接开销
  • 如果文件只需要下载一次,可在下载成功后添加停止调度的逻辑,避免无效的重复校验
  • 建议添加异常捕获逻辑,避免单次校验/下载异常导致整个调度任务终止

内容的提问来源于stack exchange,提问作者Rhea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 20:45:01