0

Trying to send mutiple requests at different times using a delay per thread:

def snipe(delay):
    print("Exact drop thread opened..")
    while True:
        if int(round(time.time() * 1000)) == int(droptime - delay):
            send = requests.post("www.example.com")
            print(f"{time.strftime('[%H:%M:%S]')}Exact:  {send}")
            break

droptime variable is in UNIX time, example: 1595359842794

For some reason only half of the threads actually send the request the others just dont trigger the if statement for some reason.

Can someone suggest a better way of sending a request at a specific time with adjustable delay.

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
teac
  • 45
  • 5
  • 2
    Don't loop waiting for a time. That uses your entire CPU waiting for the time to arrive. Instead, figure out how long it is until the desired time to arrive, then use `time.sleep()` to wait that long. – kindall Jul 21 '20 at 19:38
  • [This question](https://stackoverflow.com/questions/11523918/python-start-a-function-at-given-time) seems like it might help. – FailureGod Jul 21 '20 at 20:10

1 Answers1

3

As @kindall said, 'doing nothing' in a while loop is a bad practice, consuming CPU all the time. Using time.sleep usually is better in such situations (although there are better and somewhat more sophisticated options like async approach that lead to elegant solutions). In your case though, I'm not sure what exactly you want to achieve, but if you're trying to send requests without blocking each other then the following should work:

def snipe(delay):
    print("Exact drop thread opened..")
    send = requests.post("www.google.com")
    print(f"{time.strftime('[%H:%M:%S]')}Exact:  {send}")
    
threads = []
for i in range(5):
    t = mt.Thread(target=snipe, args=(i,))
    threads.append(t)
    t.start()

Basically you don't need to control the blocking/unblocking nature of these requests, as this being an I/O bound work (not needing much cpu which is a constraint with GIL, but definitely not for such tasks at this scale), will be handled by the OS, and in most cases in the best way.

If you are specific about the time delays/timestamps (which doesn't seem justified here), then you can take a look at this.

0xc0de
  • 8,028
  • 5
  • 49
  • 75