Below code attempts to get a connection every 5 seconds. The getConnection method returns true or false depending on random double and is for illustrative purposes. The time it takes to get a connection cannot be guaranteed so if fail to initially get connection, wait 5 seconds and try again. Once the connection is attained, then just exit.
Is there better/cleaner method of getting the connection instead of using if statements and Thread.sleep ? It seems wrong (im not sure why) sleeping the running thread for 5 seconds before trying again
public class TestAlive {
public static void main(String args[]) {
while (true) {
try {
if (getConnection()) {
System.out.println("Got connection, do some work.....");
System.exit(0);
}
else {
System.out.println("No connection, re-trying in 5 seconds");
Thread.sleep(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static Boolean getConnection() {
return Math.random() > 0.5;
}
}
Aucun commentaire:
Enregistrer un commentaire