Skip to content
← Back to Community
Async possible?
Profile icon
QuantumCodes

if i want to ping many websites at once (using requests library) it takes a long time.. is it possible that it first pings web1, then withoutnwaiting for output, pings 2 then waits till both gets pinged?

Current code: how do i change it?

import requests, sleep websites = ["web1","web2"] while True: for i in websites: try: requests.get(i,timeout=1) except: print('timeout error') time.sleep(0.5)

Takes approx 0.5 to 0.8 or even 1 second to complete 1 loop of while true excluding time.sleep

Answered by InvisibleOne [earned 5 cycles]
View Answer
Voters
Profile icon
QuantumCodes
Comments
hotnewtop
Profile icon
InvisibleOne

I would try threading, that way you can run a whole bunch of threads.

import threading import requests import time # not sleep def ping(website): try: requests.get(website, timeout=1) except: print(f"Timeout error with website {website}") while True: for i in websites: thread = threading.Thread(target=ping, args=[i]) thread.start() thread.join() time.sleep(0.5)

This way it won't wait for that thread to be done, it will just move on to creating another thread without waiting for that ping to be made.

Profile icon
QuantumCodes
Profile icon
QuantumCodes

Is threading better thatn asyncio? @InvisibleOne

Profile icon
QuantumCodes

@InvisibleOne wait..... thread.join() waits. Is there anything wrong?

Profile icon
InvisibleOne

I didn't mean to put that in there, this code was adapted from another program I wrote and I just left that there. @QuantumCodes

Profile icon
InvisibleOne

I haven't really used asyncio so I don't know which one is better @QuantumCodes

Profile icon
QuantumCodes
Profile icon
Coder100

You can use threading, like this:

from threading import Thread websites = [] def ping_website(link): # add code to ping website for i in websites: t = Thread(target=ping_website, args=(link)) t.start()

also never ever ping a website every half second -- that's on the verge of making the website crash. Make it do every 5 minutes.

Profile icon
QuantumCodes

@Coder100 oh.. mat1 pinger pings every 5 secs, so i didnt think this will happen xD thx!

Profile icon
QuestionableNS

try using asyncio

Profile icon
QuantumCodes

@QuestionableNS ? Any sample code?

Profile icon
QuestionableNS

@QuantumCodes
import asyncio
async def main():
while True:
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())

Profile icon
QuantumCodes

i will try and tell. Thx @QuestionableNS