How to Sleep Just One Function of the Code in Python?

How to Sleep Just One Function of the Code in Python?

i am writing a code in python and i just want one function to sleep not the whole code in time.sleep(). but i couldn't find a way. my code:

from time import sleep
a = int()
def calc(a,b):
    while True:
         a=a*b
         if a >> 12:
              sleep(12)
              #i just want this func to sleep here.
def print(msg):
    while True:
          msg = a
          print(msg)
          #i don't want this func to sleep

what should i do?

3

3 Answers

Use asyncio

import asyncio

async def calc(a,b):
while True:
     a=a*b
     if a >> 12:
          await asyncio.sleep(12)

I think You need to read a little about the function time.sleep. Here's what the documentation says about it:

Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

The function pauses the program at the desired place, if you call it. It does not stop the other function.

code inside f1() function will be executed 2 seconds after running the code, but in that time f2() function will be executed.

from time import time, sleep
def f1():
    print("Function1")
def f2():
    print("Function2")

t1 = time() # Stores current system time in seconds
print(t1)

time_to_delay_f1 = 2
while True:
    if time()-t1 > time_to_delay_f1:  # time()-t1 is the time passed after assigning t1 = time(), [see before 2 lines]
        f1()
    else:
        f2()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.