开发者

Doing something every 60 seconds, asynchronously

Here is a basic sample of code to show the base of the IRC bot I have running:

s=socket.socket()
s.connect((foo, 1234))
s.send('NICK开发者_JAVA百科 foo\r\n')
s.send('USER foo bar baz :qux\r\n')

while True:
    readbuffer=readbuffer+s.recv(1024)
    temp=string.split(readbuffer, "\n")
    readbuffer=temp.pop()

    for line in temp:
        line=string.rstrip(line)
        line=string.split(line)

        if(line[0]=="PING"):
            s.send("PONG %s\r\n" % line[1])

This works fine, however, say I wanted to perform a command to send a message every 60 seconds, how should I go about it? I assume this would somehow have to be done asynchronously, out of the infinite loop?


I suggest reading this article. It goes over the details of coroutines, and asynchronous processing in python. Included is a bunch of sample python code that you can play with.


Yes, you could. And yes, it would be outside the loop unless you wanted to time out the 60-second interval inside the loop by, say, checking the clock every once in a while. I would set up an interval timer such that it would call your every-60-second message function and then let that function do the send asynchronously, as you say. There might be synchronization (a different kind of sync :-) issues with the sends that are happening inside the loop, but in theory it will work just great!


You can just use a thread to run it asynchronous.

A good example about it: http://g-off.net/software/a-python-repeatable-threadingtimer-class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜