eugene
eugene

Reputation: 41755

Is it ok to use sleep() in a loop to be nice?

I couldn't describe the question better.

this is from redis-py github page.

>>> while True:
>>>     message = p.get_message()
>>>     if message:
>>>         # do something with the message
>>>     time.sleep(0.001)  # be nice to the system :)

I thought this style of coding (sleep in a loop) isn't so great, but this library leaves me no other option than to use this style. (at least they suggest it this way)

Is this ok to live with?

https://github.com/andymccurdy/redis-py

Upvotes: 1

Views: 649

Answers (2)

Carsten
Carsten

Reputation: 18446

No need to sleep in this case! The docstring for get_message says that you can specify a timeout parameter and the function will wait for timeout seconds before returning.

while True:
    message = p.get_message(timeout=0.1) # or however long you'd want to wait
    if message:
        # do something with the message

If you do not insist on using get_message, there is the listen method, which will block until the next message arrives. Actually, its usage is explained on the project's Github page right below the code example you've posted. It's just used like any other iterator:

for message in p.listen():
    # do something with the message

Upvotes: 5

Heinzi
Heinzi

Reputation: 172468

Yes, it's OK, if the library does not offer an alternative.

  • Busy waiting without sleeping is very evil, because it uses up a huge amount of CPU time.

  • Busy waiting with sleeping is not very elegant, but the CPU load is almost always negligible.

Upvotes: 3

Related Questions