0

Is there any way to make a timer that updates every second so i can see for how long my program is running. I tried making a loop:

i = 0
for i in range(1000000):
    i += 1
    time.sleep(1)

And then I want to print it into my discord.py bot. This is how it looks like:

async def on_ready():
    os.system('cls')
    print('', fg('red'))
    print(' _____ _                         ', fg('red'))
    print('|  ___| | __ _ _ __  _ __  _   _ ', fg('red'))
    print("| |_  | |/ _` | '_ \| '_ \| | | |", fg('red'))
    print('|  _| | | (_| | |_) | |_) | |_| |', fg('red'))
    print('|_|   |_|\__,_| .__/| .__/ \__, |', fg('red'))
    print('              |_|   |_|     |___/ ', fg('red'))
    print(f'Up-Time: {i}')
    print(f'Version: {version}', fg('blue'))
    print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~', fg('green'))
    print('[Server]: The Bot is online.', fg('green'))

"Up-Time" is the place where i want the time to be displayed but when i try to run it, nothing shows up. But when i put print(i) below my loop, the only thing it does is print out the numbers, without the actual server running.

Sorry if the explanation is not good enough, im super new to StackOverFlow and programming in general. And sorry if it bothers you, thank you in advance!

ツTruePvP
  • 13
  • 2

2 Answers2

0

You should never use time.sleep with discord.py because it will stop the entire bot you should use await asyncio.sleep(1).

Also you can create this command.

import datetime as dt

bot.launch_time = dt.datetime.utcnow()


@bot.command()
async def uptime(ctx):
    delta_uptime = dt.datetime.utcnow() - bot.launch_time
    hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
    minutes, seconds = divmod(remainder, 60)
    days, hours = divmod(hours, 24)
    await ctx.send(f"{days}d, {hours}h, {minutes}m, {seconds}s")

Now you can use {prefix}uptime it will tell how long it has been up.

Abdulaziz
  • 3,363
  • 1
  • 7
  • 24
0

You can get this done by multi-threading. You have you function running along side your time and both terminates immediately the function is done running:

import threading 
import time 

def calc(): #this function generates the square of all numbers between 1 and 56000000
    for i in range(1,56000000):
    i*i

t1 = threading.Thread(target=calc) 
t1.start() #starting a thread with the calc function
i = 1
while t1.is_alive(): #Check if the thread is alive
    time.sleep(1)# print time after every second
    print(f'Time elapsed ----------- {i}s')
    i = i+1
t1.join() #terminate thread once calc function is done 
print('Done!')
Seyi Daniel
  • 2,259
  • 2
  • 8
  • 18