TransWikia.com

Python exact time usage

Stack Overflow Asked by teac on November 12, 2021

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.

One Answer

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.

Answered by 0xc0de on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP