Skip to content

Instantly share code, notes, and snippets.

@XiaochenCui
Forked from jdavisp3/twisted_exercise.py
Last active September 26, 2016 06:48
Show Gist options
  • Save XiaochenCui/7a2a080ccfcf6a9b47e9b54bb56006db to your computer and use it in GitHub Desktop.
Save XiaochenCui/7a2a080ccfcf6a9b47e9b54bb56006db to your computer and use it in GitHub Desktop.
My solution to Excercise #2 at http://krondo.com/our-eye-beams-begin-to-twist/
# -*- coding: utf-8 -*-
from twisted.internet.task import LoopingCall
class Countdown(object):
_instances = set()
def __init__(self, count_to):
self.counter = count_to
self.loop_call = LoopingCall(self.count)
Countdown._instances.add(self)
def start(self, delay):
self.loop_call.start(delay)
def count(self):
# 如果计数完成
if self.counter == 0:
# 从_instances中移除self
Countdown._instances.remove(self)
# 如果_instance为空,停止rector
if not Countdown._instances:
reactor.stop()
# 停止当前loop_call
self.loop_call.stop()
elif self.counter:
print id(self), ':', 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