首页 > 解决方案 > jnotify - 检测到文件时使用其他任何东西代替 Thread.Sleep

问题描述

我真的需要一些帮助。

我采用了 JNOTIFY 方法来检测目录中的任何新文件。当文件到达时,侦听器通知该位置有一个新文件。

  @BeforeTest(alwaysRun=true)
public void Polling() throws Exception {
    ListenToNotifications.checkFolderPickup();
}

我尝试过这个,我添加了对我的设置函数的调用,以便在检测到文件后调用我的设置函数。

            //snippet from Listener Class from checkFolderPickup();
            public void fileCreated(int wd, String rootPath, String name) {
       print("New File just created " + rootPath + " : " + name);
        Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
        try {
            BaseTest.setup();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我的问题是 //Thread.sleep(1000000) 我觉得这不是一种安全的方法,我想知道是否有任何其他方法可以用来代替 Thread.Sleep,因为必须执行此函数一旦每次有新文件可用并且最终将删除旧文件等等,我无法将 Sleep 设置为 short ,它只会忽略并继续 Base.Setup()

public static void checkFolderPickup() throws Exception {
...removed other code
    
    boolean watchSubtree = true;
    int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener());
    //Thread.sleep(1000000);
    Thread.sleep(20000);
    boolean res = JNotify.removeWatch(watchID);
    if (!res) {
        // invalid watch ID specified.
    }

}

我基本上需要我的框架来继续轮询该目录,并且每次它将执行基本设置过程并遵循工作流程,删除文件然后再次轮询等等。

有人可以请教吗?

标签: javaseleniumpollingjnotify

解决方案


您不需要任何其他模块,您可以使用自定义预期条件:## 使用:

导入java.io.File;

在任何 pageobject 类中定义方法:

private ExpectedCondition<Boolean> newfilepresent() {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            File f = new File("D:\\workplace"); 
            return f.listFiles().length>1;
        }
        
        @Override
        public String toString() {
          return String.format("wait for new file to be present within the time specified");
        }
    };
}

我们创建了一个自定义的预期条件方法,现在将其用作:

并在代码中等待:

wait.until(pageobject.filepresent());

输出:

失败的:

在此处输入图像描述

通过

在此处输入图像描述


推荐阅读