Created
February 2, 2016 15:51
-
-
Save sjeandeaux/4aa32793e02ca8495ac2 to your computer and use it in GitHub Desktop.
Verify socket with scala
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
object IsUp { | |
class RetryException(msg: String, exception: Throwable) extends Exception(msg, exception) | |
def socket(host: String, port: Int, nb: Int = 10, time: Long = 1000): Unit = { | |
retry(nb, time) { | |
val socket = new Socket() | |
try { | |
socket.connect(new InetSocketAddress(host, port)); | |
} finally { | |
socket.close() | |
} | |
} | |
} | |
import scala.util.Try | |
import scala.util.Success | |
def retry[T](nb: Int = 1, time: Long = 0)(fn: ⇒ T): Try[T] = { | |
Try { | |
fn | |
} match { | |
case x: Success[T] ⇒ x | |
case _ if nb > 1 ⇒ { | |
Thread.sleep(time) | |
retry(nb - 1, time)(fn) | |
} | |
case fail ⇒ throw new RetryException(s"retry fails '$nb' '$time'", fail.failed.get) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment