[英]Python exact time usage
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
droptime 变量在 UNIX 时间,例如:
1595359842794
For some reason only half of the threads actually send the request the others just dont trigger the if statement for some reason.出于某种原因,只有一半的线程实际上发送了请求,而其他线程由于某种原因只是不触发 if 语句。
Can someone suggest a better way of sending a request at a specific time with adjustable delay.有人可以建议一种在特定时间以可调节延迟发送请求的更好方法。
As @kindall said, 'doing nothing' in a while
loop is a bad practice, consuming CPU all the time.正如@kindall 所说,在
while
循环中“什么都不做”是一种不好的做法,它一直在消耗CPU。 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).在这种情况下,使用
time.sleep
通常会更好(尽管有更好的和更复杂的选项,例如导致优雅解决方案的异步方法)。 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.基本上,您不需要控制这些请求的阻塞/解除阻塞性质,因为这是一项 I/O 绑定工作(不需要太多 cpu,这是 GIL 的一个限制,但绝对不适用于这种规模的任务),将由操作系统处理,并且在大多数情况下以最佳方式处理。
If you are specific about the time delays/timestamps (which doesn't seem justified here), then you can take a look at this .如果您具体了解时间延迟/时间戳(这里似乎不合理),那么您可以看看这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.