見出し画像

gptを使って、タイマーを作ってみた。

おはようございま~す★

Simple Countdown Timer
Here is an example of a simple countdown timer using the time module:

python
コードをコピーする
import time

def countdown_timer(seconds):
while seconds:
mins, secs = divmod(seconds, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
seconds -= 1

print("Time's up!")

Example usage: countdown from 10 seconds

countdown_timer(10)
Timer with threading Module
For a more advanced use case, you might want to run the timer in a separate thread. This way, your program can continue to do other tasks while the timer is running.

Here is an example using the threading module:

python
コードをコピーする
import time
import threading

def countdown_timer(seconds):
def run():
nonlocal seconds
while seconds:
mins, secs = divmod(seconds, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
seconds -= 1
print("Time's up!")

timer_thread = threading.Thread(target=run)
timer_thread.start()
return timer_thread

Example usage: countdown from 10 seconds

timer_thread = countdown_timer(10)

Do other tasks here

for i in range(5):
print(f"Doing other task {i+1}")
time.sleep(2)

Wait for the timer to finish if necessary

timer_thread.join()
Explanation:
Simple Countdown Timer:

The countdown_timer function takes the number of seconds as an argument.
It uses a while loop to keep updating the timer.
divmod is used to convert the total seconds into minutes and seconds.
print(timer, end="\r") prints the timer on the same line.
time.sleep(1) pauses the loop for one second before continuing.
Timer with threading Module:

The countdown_timer function starts a new thread that runs the timer.
This allows the main thread to continue executing other tasks.
nonlocal seconds is used to modify the seconds variable within the nested run function.
The main thread can perform other tasks while the timer is running in the background.
timer_thread.join() is used to wait for the timer to finish if necessary.
You can choose either implementation based on your needs. The first one is straightforward and easy to use for simple tasks, while the second one is more flexible and suitable for more complex applications where you need concurrency.

ref

https://chatgpt.com/c/195a3234-3ce1-4424-acc3-f31dd4c46b46


この記事が参加している募集

#GPTsつくってみた

1,469件

この記事が気に入ったらサポートをしてみませんか?