我试图在Concurrent::ScheduledTask#execute
方法中调用一个块,但块本身永远不会被执行。
我也尝试过使用Concurrent::ScheduledTask#new
方法,但结果是一样的。我觉得这里可能有一个我遗漏的基本问题。任何帮助将非常感激!
require 'concurrent'
##
# A basic Event
class Event
attr_accessor :ticks
# @param ticks [Numeric] The amount of ticks we wait before executing this event
def initialize(ticks = 1.0)
@ticks = ticks
puts "Event created with #{@ticks} ticks"
end
# Calls the block of this event for execution.
def execute(&block)
if !block_given?
raise AbstractEventExecution.new(self)
else
Concurrent::ScheduledTask.execute(@ticks *= 0.75) { block.call }
puts "Executed in #{@ticks} ticks"
end
end
end
class AbstractEventExecution < StandardError
attr_accessor :event
def initialize(event)
@event = event
super("The Event #{event} was not provided an execution block and is abstract.")
end
end
event1 = Event.new(105)
event2 = Event.new(1000)
event3 = Event.new(50)
event1.execute { puts "hai from event 1" }
event2.execute { puts "hai from event 2" }
event3.execute { puts "hai from event 3" }
输出如下:
Event created with 105 ticks
Event created with 1000 ticks
Event created with 50 ticks
executing an event...
Executed in 78.75 ticks
executing an event...
Executed in 750.0 ticks
executing an event...
Executed in 37.5 ticks
我不确定为什么puts "hai from event x"
根本没有显示。此外,执行此操作时没有延迟。应该分别有 78.75、750.0 和 37.5 秒的延迟,根本没有!