Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from twisted.internet.task import LoopingCall
class Countdown(object):
loops = 0
counters = 0
def __init__(self,count_to=None):
self.counter = count_to
self.loop_call = None
Countdown.loops += 1
# just to identify counters
Countdown.counters += 1
if _id is not None:
self._id = _id
else:
self._id = Countdown.counters
def count(self):
# if we done with counting
if not self.counter:
# decrease loop_calls counter
Countdown.loops -=1
# also stop reactor, if no loops left
if not Countdown.loops:
reactor.stop()
# stop current loop call
self.loop_call.stop()
elif self.counter:
print self._id,':', self.counter
self.counter -= 1
from twisted.internet import reactor
print 'Start!'
cnt3 = Countdown(8)
cnt3.loop_call = LoopingCall(cnt3.count).start(1)
cnt2 = Countdown(10)
cnt2.loop_call = LoopingCall(cnt2.count).start(0.5)
cnt1 = Countdown(5)
cnt1.loop_call = LoopingCall(cnt1.count).start(1.5)
reactor.run()
print 'Stop!'
@jdavisp3

This comment has been minimized.

Copy link
Owner Author

@jdavisp3 jdavisp3 commented Apr 3, 2011

from twisted.internet.task import LoopingCall

class Countdown(object):

loops = 0

def __init__(self, count_to):
    self.counter = count_to
    self.loop_call = LoopingCall(self.count)

    Countdown.loops += 1

    self._id = Countdown.loops

def start(self, delay):
    self.loop_call.start(delay)

def count(self):
    # if we done with counting
    if not self.counter:
        # decrease loop_calls counter
        Countdown.loops -=1
        # also stop reactor, if no loops left
        if not Countdown.loops:
            reactor.stop()
        # stop current loop call
        self.loop_call.stop()
    elif self.counter:
        print self._id,':', self.counter
        self.counter -= 1

from twisted.internet import reactor

print 'Start!'

Countdown(8).start(1)
Countdown(10).start(0.5)
Countdown(5).start(1.5)

reactor.run()

print 'Stop!'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment