Last active
March 4, 2024 21:39
-
-
Save isicju/ca53c0eaf4e5be96d0488e2fae338351 to your computer and use it in GitHub Desktop.
Задача с ретраем.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Допустим есть функция: | |
public boolean doSomething(){ | |
return System.currentTimeMillis() % 2 == 0; | |
} | |
Напишите функцию doSomethingWithRetry которая пытается вызвать doSomething(). Если doSomething() возвращает false тогда ваша функция | |
должна попробовать вызвать её еще раз пока та не вернет true. Функция получает на вход максимальное количество | |
попыток и ожидание между попытками например 1 секунду. Если все попытки закончились то функция должна вернуть false. | |
public boolean doSomethingWithRetry(int attempts, int secondsBetweenAttempts) { | |
// return false; | |
} |
my solution
public boolean doSomething() {
return System.currentTimeMillis() % 2 == 0;
}
public boolean doSomethingWithRetry(int attempts, int secondsBetweenAttempts) throws InterruptedException {
for (int i = 0; i < attempts; i++) {
boolean b = doSomething();
if (b) return true;
Thread.sleep(secondsBetweenAttempts * 1000L);
}
return false;
}
Retry(Retry(Retry :)))
public class RetryRecursive {
public static boolean doSomething() {
return System.currentTimeMillis() % 2 == 0;
}
public static boolean doSomethingWithRetry(int attempts, int secondsBetweenAttempts) throws InterruptedException {
Thread.sleep(secondsBetweenAttempts * 1_000);
return doSomething() ? true : attempts > 0 && doSomethingWithRetry(attempts-1, secondsBetweenAttempts);
}
public static void main(String[] args) throws InterruptedException {
System.out.println(doSomethingWithRetry(2, 3));
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Gang of For :)