openresty的ngx.timer.at真是個強大的方法。
- 例如某些函數不可以在一些NGINX的執行階段使用時,可以ngx.timer.at API 創建一個零延遲的timer,在timer中去處理。
- 遇到一些高延遲的函數,因為定時調用是在后台運行,並且他們的執行不會增加任何客戶端的響應時長
local function save_message(premature)
ngx.sleep(5)
local file = assert(io.open('/tmp/test.log','a+'))
file:write(string.format("timer=====> %s %s\n", ngx.time(), "in timer"))
file:close()
end
local file = assert(io.open('/tmp/test.log','a+'))
file:write(string.format("out tomer 1=====> %s %s\n", ngx.time(), "out timer 1"))
file:close()
ngx.sleep(5)
local file = assert(io.open('/tmp/test.log','a+'))
file:write(string.format("out tomer 2=====> %s %s\n", ngx.time(), "out timer 2"))
file:close()
--ngx.sleep(5)
local ok, err = ngx.timer.at(0, save_message)
if not ok then
ngx.log(ngx.ERR, "[blm-metric] failed to create timer: ", err)
end
ngx.say("success")
結果將在5秒后返回,查看日志,每隔5秒分別打印出三次的結果,