How to add a pause in python without disrupting other code

Viewed 110

I'm attempting to make a script that keeps the times of each boss in a game through text.

an example would be:

if line == 'boss1 down':
    print('boss1 timer set for 10 seconds')
    time.sleep(10)
    print("boss1 due")

if line == 'boss2 down':
    print('boss2 timer set for 15 seconds')
    time.sleep(15)
    print("boss2 due")

However, the clear issue is that only one boss can be timed at a time. Is there a function I can use that won't disrupt the code and allow me to time multiple at a given time?

3 Answers

You can use Asynchronous function :

import asyncio

async def boss1_down():
    print('boss1 timer set for 10 seconds')
    await asyncio.sleep(10)
    print("boss1 due")
asyncio.run(boss1_down())

, add arguments to the function for timers and boss.

As @Mayank mentioned, you can also use threads, which are a bit more complex to settle but you can control them (you cannot stop or wait an async function).

From this answer

You can use threading to do asynchronous tasks.

from threading import Thread
from time import sleep

def threaded_function(line):
    if line == 'boss1 down':
        print('boss1 timer set for 10 seconds')
        time.sleep(10)
        print("boss1 due")
    if line == 'boss2 down':
         print('boss2 timer set for 15 seconds')
         time.sleep(15)
         print("boss2 due")

if __name__ == "__main__":
    thread1 = Thread(target = threaded_function, args= 'boss1 down')
    thread1.start()
    thread1.join()

    thread2 = Thread(target = threaded_function, args= 'boss2 down')
    thread2.start()
    thread2.join()
    print("thread finished...exiting")

You can use the Thread class from the built-in threading module:

from threading import Thread
import time

def timer(num, secs, line):
    if line == f'boss{num} down':
        print(f'boss{num} timer set for {secs} seconds ')
        time.sleep(secs)
        print(f"boss{num} due")

boss1 = Thread(target=timer, args=(1, 10, "boss1 down"))
boss2 = Thread(target=timer, args=(2, 15, "boss2 down"))

boss1.start()
boss2.start()

Output:

boss1 timer set for 10 seconds boss2 timer set for 15 seconds

boss1 due
boss2 due
Related