The problem is that the database does not have time to be processed and there is a call on the second circle. How to make the database processing happen and the cycle goes on. asynchronously
async def send_mes_to_users(client):
async with client:
user = 'userrrrrrrrr'
try:
if db.check_invited(name_table=table, user_name=user) != "TRUE":
await client.send_message(entity=user, message=message)
db.add_invited(name_table=table, user=user) #??????????
print(f'Sent: @{user}')
except errors.BadRequestError as e:
print(f'Error: {e}')
async def main():
await asyncio.gather(
send_mes_to_users(TelegramClient('user1', api_id, api_hash)),
send_mes_to_users(TelegramClient('user2', api_id, api_hash)),
)
asyncio.run(main())
CodePudding user response:
You are running two tasks at the same time (with gather
). You're likely to run into a race condition. If you need to synchronize a "critical section", consider using an asyncio.Lock
:
db_lock = asyncio.Lock()
async def send_mes_to_users(client):
async with client:
user = 'userrrrrrrrr'
try:
async with db_lock:
# everything inside here is protected under 'db_lock'
# the lock can only be acquired once (so this section can't run concurrently)
if db.check_invited(name_table=table, user_name=user) != "TRUE":
await client.send_message(entity=user, message=message)
db.add_invited(name_table=table, user=user) #??????????
print(f'Sent: @{user}')
except errors.BadRequestError as e:
print(f'Error: {e}')
async def main():
await asyncio.gather(
send_mes_to_users(TelegramClient('user1', api_id, api_hash)),
send_mes_to_users(TelegramClient('user2', api_id, api_hash)),
)
asyncio.run(main())
CodePudding user response:
you want the second Task to not send do userrrrr as its marked as invited? then you need to update database before awaiting send_message, as this passes control to the second task, which then checks for already invited userrrrr, and it´s not as it´s awaiting sending.