标题是相当自称的。我想构建一个始终在线脚本,这很容易。我还希望用户能够通过Web界面,更改参数和重新启动来打破循环。我该如何实现?
标准警告适用 - 我很抱歉成为一个菜鸟,我肯定会用谷歌搜索,只是为了获得有关 ctrl c 的大量结果。预先感谢您的所有帮助。
如果您想要轻量级解决方案,则可以将此初始化器放入config/initializers
:
class MyLoop
def initialize
@stop = false
@semaphore = Mutex.new
end
def self.instance
@@instance ||= new
end
def start
@semaphore.synchronize do
@thread = Thread.new do
loop until @stop
end
end
end
def stop
@semaphore.synchronize do
@stop = true
@thread.join
@stop = false
end
end
def restart
stop
start
end
def loop
#call your twitter service here
end
end
ActiveSupport.on_load(:after_initialize) do
MyLoop.instance.start
end
用loop
方法调用您的Twitter服务。然后,您可以在控制器中定义操作,以停止或重新启动循环:
def stop_twitter_service
MyLoop.instance.stop
render nothing: true
end
def restart_twitter_service
MyLoop.instance.restart
render nothing: true
end
页面上的按钮应对这些操作提出AJAX请求。
请注意,当您运行Rails控制台或加载应用程序的任何其他命令时,此循环也将开始。