I wrote a code that symbolizes sleep until 7 am. basically system will keep printing "sleeping" a few times then the clock starts ringing (system will print "Hey wake up! It's 7!" once) and then continues to print "sleeping" again. but I do not know how to set an alarm. here's what I've tried:
from time import sleep
def Type(dialog):
'''
This function will be used to add a nice typing effect
and that's all
'''
counter=0 #This value helps to find out if the sentence is finished
speed=0.04 #This value changes typing speed
for char in dialog:
sleep(speed)
print(char,end='',flush=True)
counter+=1
if counter==len(dialog):
print('') #This helps to seprate two sentences in two seprate lines
def alarm():
'''
This function have to work in backgroung
without interrupting sleeping finction
'''
sleep(5)
Type("Hey wake up! It's 7!")
sleeping()
def sleeping():
for num in range(1,61):
Type(f'Sleeping {num} . . .')
alarm()
sleeping()
This doesn't do what I want.
I want the alarm() function to countdown 5 seconds while system is printing "sleeping", after the countdown is finished I want system to print "Hey wake up! It's 7!" once and then continue to print "sleeping"
I've tried using Timer method from threading framework like such:
from time import sleep
from threading import Timer
def Type(dialog):
'''
This function will be used to add a nice typing effect
and that's all
'''
counter=0 #This value helps to find out if the sentence is finished
speed=0.04 #This value changes typing speed
for char in dialog:
sleep(speed)
print(char,end='',flush=True)
counter+=1
if counter==len(dialog):
print('') #This helps to seprate two sentences in two seprate lines
def alarm():
'''
This function have to work in backgroung
without interrupting sleeping finction
'''
Type("Hey wake up! It's 7!")
sleeping()
def sleeping():
for num in range(1,61):
Type(f'Sleeping {num} . . .')
t=Timer(5.0,alarm())
t.start()
sleeping()
It didn't work how I wanted it to.
t=Timer(5.0,alarm())
You called function alarm
and then rammed output value of that function, instead of function itself, you should use function itself as 2nd argument, consider following simple example
from threading import Timer
def alarm():
print("WAKEUP")
t = Timer(5.0, alarm)
t.start()
will after 5 second print
WAKEUP
Observe that you are exploiting fact that functions are 1st class citizens in python
, so they could be passed as arguments.