1

I tried using time.sleep(), but instead of waiting for the variable it paused the whole code, not allowing the variable to change. This is my code:

@tasks.loop(seconds=5.0) #This is the code that changes the variable (Before this block of code, the variable fedex is defined)
  global check, fedex
  fedex = int(fedex) + r.randint(-500,500)
  if(check=="0"):
    check = "1"
  else:
    check = "0"

@client.command() #This is the code in which, after the variable changes, the bot should type if the variable fedex went up or down.
async def bet(ctx, arg1):
  def new():
    global current
    if(arg1=="fedex"):
      global fedex
      current = fedex
    else:
      return
  new()
  stok = current
  if(check=="0"):
    while(check != "1"):
      time.sleep(1.0)
  elif(check=="1"):
    while(check != "0"):
      time.sleep(1.0)
  new()
  stok2 = current
  if(stok2>stok):
    await ctx.send("It went up!")
  else:
    await ctx.send("It went down.")

I can't figure out what to replace time.sleep(1.0) with.

1 Answers1

0

You can use await asyncio.sleep(1) instead. Asyncio.sleep works like time.sleep, but it doesn't block the entire code execution. It stops only one event. Meanwhile, other tasks in your event loop will continue running. While using time.sleep your entire code doesn't do anything else. However, asyncio.sleep asks the event loop to do other tasks while part of your code is "sleeping".

Great explanation with examples

RiveN
  • 2,595
  • 11
  • 13
  • 26
  • Thank you so much for the quick reply! Is that the only difference between asyncio and time.sleep, or are there more? Also, is asyncio built into discord.py or do we have to import it? – ChessPlayer1844 Dec 29 '21 at 20:23
  • It's a substitution for `time.sleep` in asynchronous programming which is a really broad topic, so you might want to read about it to understand all the differences between synchronous and asynchronous programming. Both of these are used in different situations, but they have a similar purpose - which is stopping your code. However, `asyncio.sleep` won't work in all cases. Asyncio is built in Python and you have to import it with `import asyncio`. – RiveN Dec 29 '21 at 20:56
  • Okay, thank you! – ChessPlayer1844 Dec 29 '21 at 21:58