【问题标题】:Increase timeout.rb timer within block在块内增加 timeout.rb 计时器
【发布时间】:2012-02-21 10:50:17
【问题描述】:

我正在使用带有 LCD 的 RS232 键盘进行通信。在每次按键时,我都会将按下的按键写入 LCD 以向用户提供反馈。

如果在 10 秒内没有按下任何键,我想放弃等待输入。

我写了一些代码,如果用户在 10 秒内没有完成输入多字符值,我会超时,我宁愿做的是在每次按键后给用户另外 10 秒来完成输入。

这可以使用timeout.rb吗?

require 'rubygems'
require 'serialport'
require 'timeout'

sp = SerialPort.new('/dev/tty.usbserial', 9600, 8, 1, SerialPort::NONE)

sp.write("Input:")

begin
   timeout(10) do
      input = ""
      sp.each_byte do |byte|
         #call to increase timeout.rb timer would go here
         input << byte.chr
         sp.write("Input:" + input)
      end
   end
rescue Timeout::Error
   puts "Timed out!"
   exit
end

puts input

【问题讨论】:

    标签: ruby timeout


    【解决方案1】:

    我找到了一种替代方法,可以使用Threads 而不是timeout.rb,但我有兴趣了解替代方法。

    require 'rubygems'
    require 'serialport'
    
    sp = SerialPort.new('/dev/tty.usbserial', 9600, 8, 1, SerialPort::NONE)
    
    sp.write("Input:")
    
    input = ""
    timer = Time.now + 10
    
    t = Thread.new do
      sp.each_byte do |byte|
        timer = Time.now + 10
        input << byte.chr
        sp.write("Input:" + input)
      end
    end
    
    t.kill unless Time.now < timer while t.alive?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2016-11-19
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      相关资源
      最近更新 更多