Force sleep to ignore interrupts

A

andychambers2002

I've written a simple Timer class that allows you to extend it
and then implement onMinuteChange, onHourChange etc methods
which will be executed on each new minute/hour respectively.

It works as I want when used in the main application thread.
That is, when you hit Ctr + C, it stops running. However, if
the class that subclasses it, also subclasses Thread, it breaks
in that hitting Ctrl + C interrupts the call to sleep which puts
the event loop out of sync with real time.

How can I force the sleep to stay asleep for a whole second? The
source code is below.


from threading import Thread
from datetime import datetime
from time import sleep

new_minute = lambda t: t.second == 0
new_hour = lambda t: t.minute == 0 and new_minute(t)
new_day = lambda t: t.hour == 0 and new_hour(t)
new_week = lambda t: t.weekday() == 0 and new_day(t)
new_month = lambda t: t.day == 0 and new_day(t)

class Timer:

def run(self):
t = datetime.now()
diff = t.microsecond
delay = 1.000000 - (0.000001 * diff)
sleep(delay)
self.onSecondChange()
while True:
sleep(1)
t = datetime.now()
self.onSecondChange()
if new_minute(t): self.onMinuteChange()
if new_hour(t): self.onHourChange()
if new_day(t): self.onDayChange()
if new_week(t): self.onWeekChange()
if new_month(t): self.onMonthChange()

def onSecondChange(self): pass
def onMinuteChange(self): pass
def onHourChange(self): pass
def onDayChange(self): pass
def onWeekChange(self): pass
def onMonthChange(self): pass
def onYearChange(self): pass


if __name__ == '__main__':
class TestTimer(Timer, Thread):
def onSecondChange(self):
print "second elapse: %s" % datetime.now()
def onMinuteChange(self):
print "minute elapse : %s" % datetime.now()
def onHourChange(self):
print "hour elapse : %s" % datetime.now()
t = TestTimer()
t.start()
 
J

Jeremy Sanders

It works as I want when used in the main application thread.
That is, when you hit Ctr + C, it stops running. However, if
the class that subclasses it, also subclasses Thread, it breaks
in that hitting Ctrl + C interrupts the call to sleep which puts
the event loop out of sync with real time.

Maybe you could install a signal handler to ignore ctrl+c, when required

import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
 
A

andychambers2002

Jeremy said:
Maybe you could install a signal handler to ignore ctrl+c, when required

import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)

That worked nicely. Thanks

Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top