I want to make an app that will use timer.
A button will set the timer at my pc 's time plus one minute.
The problem is that it crashes.
Run the following code and press button 'set alarm'.
Then try to close the form clicking the close button ('x') of the form.
It freezes.
I guess I'm not using correctly the threading?
Any good working solution?
A button will set the timer at my pc 's time plus one minute.
The problem is that it crashes.
Run the following code and press button 'set alarm'.
Then try to close the form clicking the close button ('x') of the form.
It freezes.
I guess I'm not using correctly the threading?
Any good working solution?
import sys
from PyQt4 import QtGui
import os
import threading
import datetime
import pygame
class MyApp(QtGui.QWidget):
def __init__(self):
QtGui.QMainWindow.__init__(self)
pygame.init()
pygame.mixer.init()
now = datetime.datetime.now()
hour = now.hour; minute = now.minute; second = now.second
# add pusbutton
self.set_alarm_btn = QtGui.QPushButton('set_alarm_btn', self)
self.set_alarm_btn.clicked.connect(self._set_alarm_btn_clicked)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.set_alarm_btn)
def _set_alarm_btn_clicked(self):
now = datetime.datetime.now()
hour = now.hour;
minute = now.minute;
second = now.second
self.clock = Clock()
self.clock.set_alarm(hour, minute + 1, self)
self.clock.run()
def _response_to_alert(args):
print("Alert")
def ring_ring(self):
sys.stdout.write('ring ring\n')
sys.stdout.flush()
if hasattr(self, 'clock'):
self.clock._alarm_thread.cancel()
class Clock:
def __init__(self):
self.alarm_time = None
self._alarm_thread = None
self.update_interval = 1
self.event = threading.Event()
def run(self):
while True:
self.event.wait(self.update_interval)
if self.event.isSet():
break
now = datetime.datetime.now()
if self._alarm_thread and self._alarm_thread.is_alive():
alarm_symbol = '+'
else:
alarm_symbol = ' '
sys.stdout.write("\r%02d:%02d:%02d %s"
% (now.hour, now.minute, now.second, alarm_symbol))
sys.stdout.flush()
def set_alarm(self, hour, minute, parent):
now = datetime.datetime.now()
alarm = now.replace(hour=int(hour), minute=int(minute))
delta = int((alarm - now).total_seconds())
if delta <= 0:
alarm = alarm.replace(day=alarm.day + 1)
delta = int((alarm - now).total_seconds())
if self._alarm_thread:
self._alarm_thread.cancel()
self._alarm_thread = threading.Timer(delta, parent.ring_ring)
self._alarm_thread.daemon = True
self._alarm_thread.start()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
