扭曲工厂中的时间延迟

Time Delay In Twisted Factories

我不知道如何在 twisted.internet.ClientFactory

中使用 twisted.internet.loopingCall() 这样的东西

我需要编写 python 脚本来扫描目录中带有 phone 编号的传入文件,读取它们,并使用 YATE yaypm python 模块进行调用twisted图书馆。

client_factory = yaypm.TCPDispatcherFactory(start_client)
reactor.connectTCP(host, port, client_factory)
reactor.run()

其中yaypm.TCPDispatcherFactory派生自twisted.internet.ClientFactorystart_client是连接成功后执行的函数。

如果start_client只进行演示调用:

def start_client(client_yate):
    d = dialer(client_yate)
    d.call(caller, target)

一切正常。

(dialer是实现yaypm.flow逻辑的对象,完整描述放在http://docs.yate.ro/wiki/YAYPM:Bridge_and_then_unbridge)

我需要在 start_client

中写这样的东西
d = dialer(client_yate)
files = os.listdir(input_directory)
for filename in files:
    <read caller and target numbers from file>
    d.call(caller, target)
    time.sleep(interval)

我知道在主线程中使用睡眠函数会导致死锁。 我应该如何实现上面的算法?

如果将

twisted.internet.task.deferLaterinlineCallbacks 装饰器一起使用,它的行为类似于 sleep() 调用。这是一个使用 ClientFactory:

的简化示例
from twisted.internet import reactor, task
from twisted.internet.defer import inlineCallbacks
from twisted.internet.protocol import Protocol, ClientFactory


class DoNothing(Protocol):
    def __init__(self, connection_callback):
        self.connection_callback = connection_callback

    def connectionMade(self):
        self.connection_callback()
        return


class ConnectionClientFactory(ClientFactory):
    def __init__(self, connection_callback):
        self.connection_callback = connection_callback

    def buildProtocol(self, addr):
        return DoNothing(self.connection_callback)



def sleep(delay):
    # Returns a deferred that calls do-nothing function
    # after `delay` seconds
    return task.deferLater(reactor, delay, lambda: None)


@inlineCallbacks
def repeat_forever(message):
    while True:
        print(message)
        yield sleep(1)


if __name__ == '__main__':
    repeat_forever('running')

    factory = ConnectionClientFactory(lambda: repeat_forever('connected'))
    reactor.connectTCP('example.com', 80, factory)
    reactor.run()

上面的代码本质上是你的库对你传入的回调所做的。正如你所看到的,对 repeat_forever('running') 的调用与客户端连接后调用的调用同时运行。