ruby - 如何处理 Sinatra 中的陷阱
问题描述
我想捕获陷阱并且需要在退出我的 Sinatra 应用程序之前执行自定义代码。在退出 Sinatra 之前,我需要等到我的线程执行完成。
require 'sinatra'
trap('INT') do
puts "Trapped"
@th.join
exit(99)
end
get "/test" do
"Hello World!"
@th = Thread.new {sleep 30}
puts @th
end
如果我按Ctrl+C它应该等到线程完成。
解决方案
您可以at_exit
在应用关闭之前运行代码。
如果您需要使用at_exit
直到运行时才有的变量,您可以尝试将它们设为全局变量。例如,
thread = nil
at_exit do
puts "Trapped"
thread.join if thread
exit(99)
end
require 'sinatra'
get "/test" do
"Hello World!"
thread = Thread.new {sleep 30}
puts thread
end
推荐阅读
- python - django如何将多个值添加到多对多关系
- node.js - 带有 npm 脚本的 Node JS Chrome 调试器
- jupyter-notebook - Chrome 中的 Jupyter 笔记本
- vue.js - 带有 Bulma 下拉菜单的 Vue v-for
- google-apps-script - Google App Scripts OnEdit 触发器帮助避免“太多同时调用”
- ios - 按下按钮时奇怪的崩溃
- python - 如果单元格数据匹配,比较 2 个数据框列并在一个数据框中添加一个新列作为“是”或“否”
- javascript - 如何在不重新加载/刷新网页的情况下将数据插入 MongoDB 服务器并显示在 html 表上
- batch-file - 如何检查文件夹大小并将其与已知大小进行比较并回显通过或失败 - 批处理脚本?
- r - 可视化优化路径直到在 R 中收敛