-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.py
83 lines (73 loc) · 3.33 KB
/
timer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import asyncio
from aioconsole import ainput
from broker import tattle, tattle_str, help, toast_it
import time
class Timer:
def __init__(self, duration, username):
self.minutes = duration
self.username = username
self.stop_reason = "UNDEFINED"
self.stop_time = None
self.timer_seconds = duration * 60
self.time_start = time.time()
self.time_end = self.time_start + self.timer_seconds
async def time_left(self):
seconds_left = self.time_end - time.time()
minutes_left = seconds_left / 60
tattle("", f"{round(minutes_left, 1)} minutes left ({int(seconds_left)} sec.)", 1)
async def timer(self, duration):
time_start_str = time.strftime('%H:%M:%S', time.localtime(self.time_start))
time_end_str = time.strftime('%H:%M:%S', time.localtime(self.time_end))
title = f"Timer started for {duration} minutes. >>> "
message = f"It has started at {time_start_str} AND will end at {time_end_str}."
tattle("", title, 0)
tattle("", message, 1)
toast_it(title, message)
await asyncio.sleep(self.timer_seconds)
print("TIMER ENDED")
async def get_input(self):
while True:
user_input = await ainput(tattle_str(str(self.username), "[COMMAND] (help?) >>> "))
match user_input:
case "stop":
self.stop_reason = await ainput(tattle_str(str(self.username), "[REASON?] >>> "))
return
case "help":
help()
case "define":
self.description = await ainput(tattle_str(str(self.username), "[DESCRIPTION] >>> "))
case "time":
await self.time_left()
case "cancel":
self.stop_reason = "cancelled"
tattle("", "Quitting unconditionally!", 1)
return
case "tired":
print("WORK IT OUT! Need to implement better methodology!!")
case _:
tattle("", "Please, type 'stop' to end the timer", 1)
async def main(self):
duration = self.minutes
timer_task = asyncio.create_task(self.timer(duration))
input_task = asyncio.create_task(self.get_input())
await asyncio.wait([timer_task, input_task], return_when=asyncio.FIRST_COMPLETED)
finish_title = "<(-)(-)> Timer finished! "
finish_message = ""
if not timer_task.done():
# If the timer task is not done, it means the input task completed first
# So, we cancel the timer task
timer_task.cancel()
try:
await timer_task
except asyncio.CancelledError:
if self.stop_reason == "cancelled":
tattle("", "Timer was cancelled", 1)
return self.time_start, self.time_end, self.stop_time, self.stop_reason
else:
finish_message = "Timer cancelled. The cause it: " + str(self.stop_reason)
tattle("", finish_message, 1)
else:
finish_message = "Timer finished successfully!"
tattle("", finish_title, 1)
toast_it(finish_title, finish_message)
return self.time_start, self.time_end, self.stop_time, self.stop_reason