Ruby 如何判断方法或循环是否已完成?
我写的阿鲁比程序有个奇怪的问题 基本上,这个想法是让程序在后台持续运行。该程序每30秒检查一次我的浏览器历史记录,并将任何新的历史记录项上载到服务器Ruby 如何判断方法或循环是否已完成?,ruby,Ruby,我写的阿鲁比程序有个奇怪的问题 基本上,这个想法是让程序在后台持续运行。该程序每30秒检查一次我的浏览器历史记录,并将任何新的历史记录项上载到服务器 # client.rb history = HistoryUploader.new(Chrome) # Run everything loop do history.run sleep 30 end HistoryUploader类的重要部分如下所示 class HistoryUploader def run upload_h
# client.rb
history = HistoryUploader.new(Chrome)
# Run everything
loop do
history.run
sleep 30
end
HistoryUploader
类的重要部分如下所示
class HistoryUploader
def run
upload_history until local.last_seen_history_item == server.last_seen_history_item
end
def upload_history
# POST batches of history items to the server
end
end
我看到这段代码的主要问题是,如果HistoryUploader.run
需要超过30秒才能完成(这很可能是因为它正在发送多个http请求),client.rb
中的外部循环将再次尝试调用run
,我可能会收到到服务器的并行请求,这会让事情变得非常混乱
有没有一种方法可以阻止
run
方法被调用两次,直到调用完成?我会使用一个请求队列,一个接一个地执行请求。您还可以在HistoryUploader中放置一个简单的布尔标志,例如@is_Uploader:
class HistoryUploader
attr_accessor :is_uploading
def initialize
@is_uploading = false
end
def run
if @is_uploading
return
end
upload_history until local.last_seen_history_item == server.last_seen_history_item
end
def upload_history
@is_uploading = true
# POST batches of history items to the server
# On uploading finished:
@is_uploading = false
end
end
如果确实要阻止主循环直到上载完成,则可以调度线程并使用join等待其完成:
require 'thread'
t = Thread.new do
#post to server
end
t.join
我不认为你有你认为你有的问题。描述代码的方式仍然是单线程的。您没有启动新线程来执行history.run,这意味着在history.run方法返回之前,将不会执行sleep 30 是否需要基于此线程取决于您正在寻找的行为。如果您想在history.run完成30秒后触发对history.run的另一个调用,您的代码将立即执行该操作。如果希望每30秒独立于history.run的执行时间运行一次(例如,history.run需要7.5秒,因此希望在22.5秒后再次运行查询),那么线程化解决方案可能是最优雅的