I am trying to run two threads concurrently in order to: collect data and save this data periodically. I am using socket to collect the data and module asyncio in order to run in parallel this two functions.
This is the code:
# IMPORT LIBRARIES:
import socket
import asyncio
# DEFINITION FUNCTION:
async def restart_variable():
print("executes restart_variable")
while True:
await asyncio.sleep(20)
print("Should clean and save data")
print("For the moment only clean")
totaldata = ""
async def collect_data():
print("executes collect data")
totaldata = ""
while True:
data = sock.recv(1024)
data = str(data, "utf-8")
totaldata += data
print(1, len(totaldata))
print(2, data)
async def main():
try:
sock.connect((HOST, PORT))
print("Connected")
except Exception as e:
print("Cannot connect to the server:", e)
try:
asyncio.gather(restart_variable(), collect_data())
except KeyboardInterrupt:
print("Manually interrupted")
sock.close()
except Exception as e:
print(e)
sock.close()
HOST = "HOST"
PORT = 2304
# MAIN EXECUTION:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
asyncio.run(main())
However, only collect data is working. restart_variable function is only executed one time. I dont understand why while True has no effect.