Integrating event_add_timer, am I doing this right?

Hi,

So I have module where I need a certain number of events only to run
every 1 second. As of right now I am running them on every request and
it’s using a mutex lock. So at 500 requests a second you can see where
this is unnecessary and causing a problem.

So after some research I attached my own method to the “init process”
handler. I then noticed it’s called for each worker process, so whatever
worker_processes is equal to. So in my case my method was being called
16 times.

Now I do not need to attach it to 16 processes, only one. So I created a
shared memory that would store the pid of the first process. If the next
worker sees a PID is already set then it returns.

Then I attach my method to event_add_timer to have it run every second.

This is working great, and with workers I only have one of the workers
timing my method every second.

Now my question is, was this the right way to go about this? Here is my
code for the init process handler.

/* Initialize process */
static ngx_int_t ngx_http_mymodule_init_proc(ngx_cycle_t *cycle)
{

// There is already an event owner set.
if(ngx_http_mymodule_shm->event_owner)
return NGX_OK;

// Set the event owner.
ngx_http_mymodule_shm->event_owner = ngx_pid;

// Let’s try to add a timer just for fun.
ngx_http_mymodule_timer->log = cycle->log;
ngx_http_mymodule_timer->data = “”; // Blank for now
ngx_http_mymodule_timer->handler = ngx_http_mymodule_timer_test;
ngx_add_timer(ngx_http_mymodule_timer, 1000);

return NGX_OK;
}

Posted at Nginx Forum:

I need to allocate some memory inside the event, can i use the
cycle->pool?

Posted at Nginx Forum:

I think I figured this out on my own, there posed an issue if a worker
thread died. NGINX will automatically respawn a new one, and I need to
make sure the event attaches to the new one. This code ended up working
good.

// There is already an event owner set.
if(dosstop_shm->event_owner)
{
// Does the PID still exist?
for (s = 0; s < ngx_last_process; s++) {
if (ngx_processes[s].pid == dosstop_shm->event_owner &&
!ngx_processes[s].exited) {
ngx_shmtx_unlock(&shpool->mutex);
return NGX_OK;
}
}
}

Posted at Nginx Forum: