如何创建异步“cron like”调度程序内部nginx [英] How to create asynchronous "cron like" scheduler inside nginx
问题描述
我需要在 nginx
服务器中创建一个异步调度程序来更新一个变量。让我给你一个例子,我的意思是什么,为什么我需要它。
I need to create an asynchronous scheduler inside nginx
server to update a variable. Let me give you an example what I mean by this and why I need it.
想象一下配置文件,看起来像这样:
Imagine config file that looks something like this:
http {
lua_shared_dict foo 5m;
server {
location /set {
content_by_lua '
local foo = ngx.shared.foo
ngx.say(foo:get("12345"))
';
}
}
}
我指定的变量 foo
驻留在共享内存中,所有工作进程都可以访问它。我想做的是设置这些值从 lua
脚本,将被称为每个minite。仅供参考,它将转到 Redis
,然后检索必要的数据,并更新此变量。我知道我可以在每次电话 content_by_lua
这样做,但是对于大量的流量来说效率非常低。
I specified variable foo
that resides in shared memory and all worker processes have access to it. What I want to do is to set those values from lua
script that will be called every minite. Just for reference it will be going to the Redis
and then retrieve necessary data, and update this variable. I know I can do this in content_by_lua
in every call, but it's highly inefficient for a huge volume of traffic.
我想要一个单独的过程,将触发每一分钟左右只是去一个任务。在 nginx
中有这样的东西吗?或者有什么模块可以帮助我吗?
I would like a separate process that would be triggered every minute or so to just go and one task. Is there anything like this in nginx
or are there any modules that could help me with that?
推荐答案
您可以使用ngx_lua提供的新ngx.timer API。有关详情,请参阅文档:
You can use the new ngx.timer API provided by ngx_lua. See the documentation for details:
http:// wiki .nginx.org / HttpLuaModule#ngx.timer.at
您可以在定时器处理程序中创建一个新的定时器,使定时器保持触发像cronjob ;)
You can create a new timer in your timer handler to make the timer keeps triggering like a cronjob ;)
BTW,计时器是每个工作进程,你可以在你的计时器处理程序中使用lua-resty-lock库来确保只有一个计时器是活动的所有nginx工作者中的时间: https://github.com/agentzh/lua-resty-lock
BTW, the timer is per-worker process, you can use the lua-resty-lock library in your timer handler to ensure that only one timer is active at a time among all the nginx workers: https://github.com/agentzh/lua-resty-lock
这篇关于如何创建异步“cron like”调度程序内部nginx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!