2,763
社区成员
发帖
与我相关
我的任务
分享
@c=30
@i=0
Thread.new do #收到回车就重新计数
loop do
if gets
puts " reset "
print @c
@i=0
end
end
end
puts "按回车重新计数"
loop do #每秒减1
print @c-@i
sleep 1
@i+=1
print "\r"
exit if @i >= @c
end
require 'date'
class Dog
DURATION = 3
@@id = 0
attr_accessor :fed, :id, :thread, :expired
def initialize
@id = @@id += 1
puts "[#{DateTime.now.iso8601}] Dog##{id} created"
@thread = Thread.new {
sleep DURATION
if fed
puts "[#{DateTime.now.iso8601}] Dog##{id} survives"
else
puts "[#{DateTime.now.iso8601}] Dog##{id} died"
end
self.expired = true
}
end
end
dogs = []
puts ">>> Press [Enter] to feed a dog"
dogs << Dog.new
while input = gets.chomp do
Process.exit(true) if dogs.all?(&:expired)
dogs.last.fed = true
puts "[#{DateTime.now.iso8601}] Dog##{dogs.last.id} fed"
dogs << Dog.new # Reset timer
end
基本上你需要使用Thread来建立timer,目的是不阻止你收消息的机制 (Non-Blocking)
以上代码只使用了标准库
你也可以使用现成的Gem来简化代码:
如: https://github.com/ruby-concurrency/concurrent-ruby
类似这样的 Non-Blocking 操作 在不同语言中常出现的关键词为 async/await (NodeJS, Python 和 Go 都有async)