Code cleanup.
Using distinct in query and moved sleep to a more sensible place.