问题描述
我想使用Redis的pubsub功能来实现彗星,但pubsub没有超时,所以如果我 ps.listen()
,它会阻塞,即使客户端关闭浏览器。 greenlet在产卵过程中有超时功能。但是我不知道如何将它们结合在一起。
烧瓶的伪
$ b $ ('foo')
for ps.listen()中的item:
if item ['type'] =='message':
return item ['data']
#ps.listen()会阻塞,所以如何使它在30秒后超时?
因为你不是线程假设这是有意的,并且在某些情况下是明智的),您必须使用一种中断。信号是Unix系统中的一种中断,允许你在可能阻塞的呼叫期间返回回调。
这个永远不会返回的文件的例子是符合你想要做的事情。它来自
但是一个警告。由于Python使用全局解释器锁执行操作系统信号处理,因此会遇到一些稳定性问题。这些问题通常应该是很少见的。
导入信号,os
def处理程序(signum,frame):
print'信号处理程序调用信号',signum
提高IOError(无法打开设备!)
#设置信号处理程序和一个5秒的警报
signal.signal (signal.SIGALRM,handler)
signal.alarm(5)
#这个open()可能无限期地挂起
fd = os.open('/ dev / ttyS0', os.O_RDWR)
signal.alarm(0)#禁用闹钟
I want to use Redis's pubsub feature to implement comet, but pubsub doesn't have timeout, so if I ps.listen()
, it will block, even if client closes browser.
greenlet has timeout feature when spawn process. but I don't know how to combine them together.
flask's pseudo
@app.route('/')
def comet():
rc = redis.Redis()
ps = rc.pubsub()
ps.subscribe('foo')
for item in ps.listen():
if item['type'] == 'message':
return item['data']
# ps.listen() will block, so how to make it timeout after 30 s?
Because you're not threading (and I'm assuming this is intentional and in some cases wise) you must use a type of interrupt. Signals are a type of interrupt on Unix systems to allow you to return to a callback during a call that could block.
This example of a file open which will never return is in line with what you want to do. It's taken from http://docs.python.org/library/signal.html#module-signal
But a warning. Because Python uses a Global Interpreter Lock to perform OS signal handling it is subject to some stability problems. These problems should be rare normally though.
import signal, os
def handler(signum, frame):
print 'Signal handler called with signal', signum
raise IOError("Couldn't open device!")
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)
signal.alarm(0) # Disable the alarm
这篇关于如何实现redis的pubsub超时功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!