31

I tried setting connectTimeoutMS and socketTimeoutMS to a low value but it still takes about 20 seconds before my script times out. Am I not using the options correctly? I want the script to exit after 5 seconds.

def init_mongo():
    mongo_connection = MongoClient('%s' %MONGO_SERVER, connectTimeoutMS=5000, socketTimeoutMS=5000)
    if mongo_connection is None:
        return

    try:
        <code>
    except:
        <code>
sdot257
  • 10,046
  • 26
  • 88
  • 122

2 Answers2

42

So if anyone comes across this later, I was using the wrong option.

What I was looking for is serverSelectionTimeoutMS

sdot257
  • 10,046
  • 26
  • 88
  • 122
  • 1
    Thank you! I was having exactly the same problem and could get no change in timeout using the other timeout options. This worked perfectly! – labroid Apr 27 '17 at 20:09
  • I'm getting same issue, could you help me `pymongo.errors.ServerSelectionTimeoutError: No replica set members found yet` – Sreenath Oct 04 '19 at 13:22
4

The web page: https://api.mongodb.com/python/current/api/pymongo/mongo_client.html says:

connectTimeoutMS: (integer or None) Controls how long (in milliseconds) the driver will wait during server monitoring when connecting a new socket to a server before concluding the server is unavailable. Defaults to 20000 (20 seconds)

(Where "server monitoring" is undefined)

So what? Is connectTimeoutMS sort of like a decoy to keep out the amateurs (like me)

Ben Slade
  • 478
  • 5
  • 11