D
D
daho0052021-07-04 11:08:44
Python
daho005, 2021-07-04 11:08:44

How to make a delay that does not stop the program?

The simplest code example:

import time
def wait():
    time.sleep(5)
    print(2)
while True:
    wait()
    print(1)

Question. How can I make the wait function work as if in a separate thread and not stop the while loop?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-07-04
@daho005

Run it in a separate thread.

A
Alexey, 2021-07-04
@AlekseyZz

Can the program be made asynchronous?

import asyncio


async def waiter():
    await asyncio.sleep(5)
    print(2)


async def printer():
    while True:
        await asyncio.sleep(1)
        print(1)


async def main():
    await asyncio.gather(waiter(), printer())


asyncio.run(main())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question