ngx.timer.at
syntax: ok, err = ngx.timer.at(delay, callback, user_arg1, user_arg2, …)
The first argument, delay, specifies the delay for the timer, in seconds.
One can specify fractional seconds like 0.001 to mean 1 millisecond here.
0 delay can also be specified, in which case the timer will immediately expire when the current handler yields execution.
Here is a simple example:
location / {
...
log_by_lua '
local function push_data(premature, uri, args, status)
-- push the data uri, args, and status to the remote
-- via ngx.socket.tcp or ngx.socket.udp
-- (one may want to buffer the data in Lua a bit to
-- save I/O operations)
end
local ok, err = ngx.timer.at(0, push_data,
ngx.var.uri, ngx.var.args,
ngx.header.status)
if not ok then
ngx.log(ngx.ERR, "failed to create timer: ", err)
return
end
';
}
问题是:ngx.timer.at(0, func)和直接调用func有什么区别吗?
When a timer expires, the user Lua code in the timer callback is running in a “light thread” detached completely from the original request creating the timer.
So objects with the same lifetime as the request creating them, like cosockets, cannot be shared between the original request and the timer user callback function.
A lot of the Lua APIs for Nginx are enabled in the context of the timer callbacks, like stream/datagram cosockets (ngx.socket.tcp and ngx.socket.udp), shared memory dictionaries (ngx.shared.DICT), user coroutines (coroutine.), user “light threads” (ngx.thread.), ngx.exit, ngx.now/ngx.time, ngx.md5/ngx.sha1_bin, are all allowed. But the subrequest API (like ngx.location.capture), the ngx.req.* API, the downstream output API (like ngx.say, ngx.print, and ngx.flush) are explicitly disabled in this context.
You can pass most of the standard Lua values (nils, booleans, numbers, strings, tables, closures, file handles, and etc) into the timer callback, either explicitly as user arguments or implicitly as upvalues for the callback closure. There are several exceptions, however: you cannot pass any thread objects returned by coroutine.create and ngx.thread.spawn or any cosocket objects returned by ngx.socket.tcp, ngx.socket.udp, and ngx.req.socket because these objects’ lifetime is bound to the request context creating them while the timer callback is detached from the creating request’s context (by design) and runs in its own (fake) request context. If you try to share the thread or cosocket objects across the boundary of the creating request, then you will get the “no co ctx found” error (for threads) or “bad request” (for cosockets). It is fine, however, to create all these objects inside your timer callback.