我是一名 DBA,我偶然发现了这样一种情况:开发人员运行 irb 会话(来自 Ruby on Rails 应用程序)。这个 irb 保持数据库连接打开。有时 - 他们忘记了它,它继续“运行” - 不做任何事情,但仍然使用一个数据库连接。
我想在他们的 irb 配置中添加某种“空闲超时”。是否可以?怎么做?
这是一个快速的技巧,您可以如何实现这一点。
请注意,这并没有考虑到用户可能正在 irb 会话中执行一些长时间运行的任务。它只是查看最后一次输入的时间戳;如果它没有改变,那么它只会杀死进程:
更新:它现在检查 irb 当前是否正在运行命令,如果是这种情况,则忽略任何超时。
# Add some methods to IRB::Context and IRB::Irb
# for easier timeout implementation.
class IRB::Irb
def status
@signal_status
end
end
class IRB::Context
attr_reader :irb
attr_reader :line_no
def is_evaluating?
self.irb.status == :IN_EVAL
end
end
# Implement an auto exit timer thread. Timeout is given in seconds.
module IRB
def self.auto_exit_after(timeout = 60)
Thread.new {
context = IRB.conf[:MAIN_CONTEXT]
last_input = Time.now
last_line = context.line_no
loop {
sleep 10
# Check if irb is running a command
if context.is_evaluating?
# Reset the input time and ignore any timeouts
last_input = Time.now
next
end
# Check for new input
if last_line != context.line_no
# Got new input
last_line = context.line_no
last_input = Time.now
next
end
# No new input, check if idle time exceeded
if Time.now - last_input > timeout
$stderr.puts "\n** IRB exiting due to idle timeout. Goodbye..."
Process.kill("KILL", Process.pid)
end
}
}
end
end
Run Code Online (Sandbox Code Playgroud)
要使用它,请将代码添加到.irbrc或其他一些在 irb 启动时自动加载的地方,然后启动计时器:
IRB.auto_exit_after(60)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |