w3resource

Python Simple Alarm Clock Project - Solutions and Explanations


Alarm Clock:

Design a simple alarm clock application that allows users to set alarms.

Input values:
User sets an alarm time.

Output value:
Alarm notification when the set time is reached.

Example:

Input values:
Set alarm time: 07:30 AM
Output value:
Alarm! It's 07:30 AM. Time to wake up!

Here are two different solutions for an "Alarm Clock" application in Python. The application will allow users to set a specific alarm time, and when the current time matches the alarm, it will notify the user.

Solution 1: Basic Approach Using 'while' Loop and 'time' Module

Code:

# Solution 1: Basic Approach Using `while` Loop and `time` Module

# Import necessary modules
import time  # Provides time-related functions for sleep and current time
from datetime import datetime  # Provides functions to work with date and time

# Function to get the current time in HH:MM AM/PM format
def get_current_time():
    # Use datetime to get the current time and format it
    return datetime.now().strftime("%I:%M %p")

# Function to check and trigger the alarm
def set_alarm(alarm_time):
    print(f"Alarm set for {alarm_time}. Waiting...")

    # Infinite loop to keep checking the time until the alarm time is reached
    while True:
        # Get the current time
        current_time = get_current_time()

        # Compare the current time with the alarm time
        if current_time == alarm_time:
            # Alarm notification
            print(f"Alarm! It's {alarm_time}. Time to wake up!")
            break  # Exit the loop after the alarm goes off

        # Sleep for 1 minute to avoid frequent checks
        time.sleep(60)

# Get the user input for the alarm time in HH:MM AM/PM format
alarm_time = input("Set alarm time (e.g., 07:30 AM): ")

# Set the alarm
set_alarm(alarm_time)

Output:

Set alarm time (e.g., 07:30 AM): 10:54 PM
Alarm set for 10:54 PM. Waiting...
Alarm! It's 10:54 PM. Time to wake up!

Explanation:

  • Uses a 'while' loop to continuously check the current time against the user's set alarm time.
  • The 'time.sleep(60)' function is used to pause execution for 1 minute between checks to avoid frequent checking.
  • The current time is formatted to match the user-input format using 'datetime.now().strftime("%I:%M %p")'.
  • This solution is straightforward but could block the main thread, making the program unresponsive if additional features are added.

Solution 2: Using a Class and Multithreading for Improved Responsiveness

Code:

# Solution 2: Using a Class and Multithreading for Improved Responsiveness

import time  # Provides time-related functions
from datetime import datetime  # Provides functions to work with date and time
import threading  # Provides threading for running tasks in the background

class AlarmClock:
    """Class to represent an alarm clock"""

    def __init__(self, alarm_time):
        """Initialize the AlarmClock with the set alarm time"""
        self.alarm_time = alarm_time  # Store the alarm time
        self.alarm_thread = threading.Thread(target=self.run_alarm)  # Create a thread for the alarm

    def get_current_time(self):
        """Get the current time in HH:MM AM/PM format"""
        return datetime.now().strftime("%I:%M %p")

    def run_alarm(self):
        """Check the current time and trigger the alarm when it matches the set time"""
        print(f"Alarm set for {self.alarm_time}. Waiting...")

        while True:
            # Get the current time
            current_time = self.get_current_time()

            # Check if the current time matches the alarm time
            if current_time == self.alarm_time:
                print(f"Alarm! It's {self.alarm_time}. Time to wake up!")
                break  # Exit the loop when the alarm goes off

            # Sleep for 1 minute to avoid frequent checks
            time.sleep(60)

    def start(self):
        """Start the alarm in a separate thread"""
        self.alarm_thread.start()  # Start the thread to run the alarm check

# Get user input for the alarm time in HH:MM AM/PM format
alarm_time = input("Set alarm time (e.g., 07:30 AM): ")

# Create an instance of the AlarmClock class with the provided alarm time
alarm_clock = AlarmClock(alarm_time)

# Start the alarm clock
alarm_clock.start()

Output:

Set alarm time (e.g., 07:30 AM): 11:02 PM
Alarm set for 11:02 PM. Waiting...
Alarm! It's 11:02 PM. Time to wake up!

Explanation:

  • Uses an 'AlarmClock' class to encapsulate all alarm-related functionality, making the code modular and easier to extend.
  • The 'run_alarm' method handles checking the current time in a separate thread, allowing the main program to remain responsive.
  • Uses the 'threading' module to create and start a new thread, which continuously checks for the alarm time in the background.
  • This approach provides better responsiveness and scalability, especially if additional features are planned (like multiple alarms).

Note:
Both solutions provide a way to set an alarm and notify the user when the alarm time is reached, with Solution 1 being a basic approach and Solution 2 using multithreading to offer improved responsiveness and scalability.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/projects/python/python-alarm-clock-project.php