Skip to content

Instantly share code, notes, and snippets.

@sjeandeaux
Created February 2, 2016 15:51
Show Gist options
  • Save sjeandeaux/4aa32793e02ca8495ac2 to your computer and use it in GitHub Desktop.
Save sjeandeaux/4aa32793e02ca8495ac2 to your computer and use it in GitHub Desktop.
Verify socket with scala
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