Skip to content

Instantly share code, notes, and snippets.

@isicju
Last active March 4, 2024 21:39
Show Gist options
  • Save isicju/ca53c0eaf4e5be96d0488e2fae338351 to your computer and use it in GitHub Desktop.
Save isicju/ca53c0eaf4e5be96d0488e2fae338351 to your computer and use it in GitHub Desktop.
Задача с ретраем.
Допустим есть функция:
public boolean doSomething(){
return System.currentTimeMillis() % 2 == 0;
}
Напишите функцию doSomethingWithRetry которая пытается вызвать doSomething(). Если doSomething() возвращает false тогда ваша функция
должна попробовать вызвать её еще раз пока та не вернет true. Функция получает на вход максимальное количество
попыток и ожидание между попытками например 1 секунду. Если все попытки закончились то функция должна вернуть false.
public boolean doSomethingWithRetry(int attempts, int secondsBetweenAttempts) {
// return false;
}
@polo7
Copy link

polo7 commented Mar 4, 2024

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