gpt4 book ai didi

ruby - 如何让 irb 长时间闲置后退出?

转载 作者:行者123 更新时间:2023-12-04 00:38:00 26 4
gpt4 key购买 nike

我是一名 DBA,我偶然发现了这样的案例:开发人员运行 irb session (来自 Ruby on Rails 应用程序)。这个 irb 保持数据库连接打开。有时 - 他们忘记了它,它继续“运行” - 什么都不做,但仍在使用一个数据库连接。

我想在他们的 irb 配置中添加某种“空闲超时”。可能吗?怎么做?

最佳答案

这里是一个快速技巧,您可以如何实现它。

请注意,这没有考虑到用户可能正在 irb session 中执行一些长时间运行的任务。它只是查看最后一次输入的时间戳;如果它没有改变,那么它就会完全终止进程:

更新:它现在检查 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

要使用它,请将代码添加到 .irbrc,或在 irb 启动时自动加载的其他地方,然后启动计时器:

IRB.auto_exit_after(60)

关于ruby - 如何让 irb 长时间闲置后退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22710919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com