简体   繁体   English

如何调用方法,直到每隔x分钟返回true

[英]How to call a method until it returns true every x minutes

I have a main thread which will call the below process method from a different class.. 我有一个主线程,它将从另一个类调用以下process方法。

Now what I am want to do is, if i=1 then, I will make a call to checkValue method and if it returns false , then I would like to sleep for two minutes and then again make a call to checkValue method, and if it still returns false , then again sleep for two minutes, and then again try checkValue method but now suppose if it returns true , then I would go for i=2 iteration, otherwise not. 现在我要做的是,如果i=1 ,我将调用checkValue方法,如果返回false ,那么我想睡两分钟,然后再次调用checkValue方法,如果它仍然返回false ,然后再次睡眠两分钟,然后再次尝试使用checkValue方法,但现在假设它返回true ,那么我将进行i=2迭代,否则返回。

public void process(String workflowName) {

    ..// some other code here

    for (int i = 1; i <= 10; i++) {
        try {
            .. // some other code here

            if (!checkValue()) {
                Thread.sleep(120000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


private boolean checkValue() throws Exception {
    boolean check_nodes = false;
    return check_nodes;
}

Is there any way to do this? 有什么办法吗?

I would like to go for i=2 for loop iteration only when checkValue method returns true.. So in short, I need to keep on calling checkValue method until it returns true every 2 minutes. 我只想在checkValue方法返回true时才将i=2用于循环迭代。因此,简而言之,我需要继续调用checkValue方法,直到每2分钟返回一次true。

Once it returns true, I won't call checkValue method for i=1 , but for i=2 , I will do the same thing again. 一旦返回true,就不会为i=1调用checkValue方法,但是对于i=2 ,我将再次执行相同的操作。

Thread.sleep(millis) suspends the current thread. Thread.sleep(millis)挂起当前线程。

So you have to call Thread.sleep(2 * 60 * 1000) in the main thread, to sleep for two minutes. 因此,您必须在主线程中调用Thread.sleep(2 * 60 * 1000)来睡眠两分钟。

int i = 1;
while ( i <=10 ){
    try{
         if(!checkValue()){
             Thread.sleep(120000);
         } else{
                i++;
         }
    } catch (Exception e) {
         e.printStackTrace();
    }

} }

Use break if you don't want to continue the loop. 如果您不想继续循环,请使用break

for (int i = 1; i <= 10; i++) {
    try {
        .. // some other code here

        if (!checkValue()) {
            Thread.sleep(2000 * 60);
        }
        else {
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM