【问题标题】:CherryPy kill process if not pinged in time如果没有及时 ping,CherryPy 会终止进程
【发布时间】:2012-08-15 19:39:01
【问题描述】:
有没有办法让 CherryPy(在 :8080 上运行,它只是作为 SIGUSR1 的侦听器的功能)如果某个进程在一定秒数内没有被 ping 通,则杀死它?
当然,进程终止的 Python 代码是没有问题的,只是 CherryPy 检测最后一次 ping 的方式,并不断将其与当前时间进行比较 - 如果进程在一定秒数内没有被 ping 过,则终止进程.
请注意,如果 Javascript 正在执行 ping 操作(通过 setInterval()),CherryPy 代码中的无限循环将导致 .ajax() 请求挂起和/或超时,除非有办法只使用 .ajax() ping 而不是等待任何类型的响应。
感谢你们提供的任何提示!
梅森
【问题讨论】:
标签:
javascript
process
kill
cherrypy
【解决方案1】:
好的,所以答案是设置两个类,一个更新时间,另一个不断检查时间戳是否在 20 秒内没有更新。如果整个站点不是基于 CherryPy 构建的,那么在用户离开页面后终止进程时,这非常有用。在我的例子中,它只是坐在 :8080 上监听来自 Zend 项目的 JS ping。 CherryPy 代码如下所示:
import cherrypy
import os
import time
class ProcKiller(object):
@cherrypy.expose
def index(self):
global var
var = time.time()
@cherrypy.expose
def other(self):
while(time.time()-var <= 20):
time.sleep(1)
print var
os.system('pkill proc')
cherrypy.quickstart(ProcKiller())
ping 的 JS 字面意思就是这样简单:
<script type="text/javascript">
function ping(){
$.ajax({
url: 'http://localhost:8080'
});
}
function initWatcher(){
$.ajax({
url: 'http://localhost:8080/other'
});
}
ping(); //Set time variable first
initWatcher(); //Starts the watcher that waits until the time var is >20s old
setInterval(ping, 15000); //Updates the time variable every 15s, so that while users are on the page, the watcher will never kill the process
</script>
希望这可以帮助其他人寻找类似的解决方案来处理用户离开页面后的杀戮!
梅森