Stopping gearman workers nicely

后端 未结 12 860
滥情空心
滥情空心 2021-01-30 04:24

I have a number of Gearman workers running constantly, saving things like records of user page views, etc. Occasionally, I\'ll update the PHP code that is used by the Gearman w

12条回答
  •  抹茶落季
    2021-01-30 04:35

    I use following code which supports both Ctrl-C and kill -TERM. By default supervisor sends TERM signal if have not modified signal= setting. In PHP 5.3+ declare(ticks = 1) is deprecated, use pcntl_signal_dispatch() instead.

    $terminate = false;
    pcntl_signal(SIGINT, function() use (&$terminate)
    {
        $terminate = true;
    });
    pcntl_signal(SIGTERM, function() use (&$terminate)
    {
        $terminate = true;
    });
    
    $worker = new GearmanWorker();
    $worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);
    $worker->setTimeout(1000);
    $worker->addServer('127.0.0.1', 4730);
    $worker->addFunction('reverse', function(GearmanJob $job)
    {
        return strrev($job->workload());
    });
    
    $count = 500 + rand(0, 100); // rand to prevent multple workers restart at same time
    for($i = 0; $i < $count; $i++)
    {
        if ( $terminate )
        {
            break;
        }
        else
        {
            pcntl_signal_dispatch();
        }
    
        $worker->work();
    
        if ( $terminate )
        {
            break;
        }
        else
        {
            pcntl_signal_dispatch();
        }
    
        if ( GEARMAN_SUCCESS == $worker->returnCode() )
        {
            continue;
        }
    
        if ( GEARMAN_IO_WAIT != $worker->returnCode() && GEARMAN_NO_JOBS != $worker->returnCode() )
        {
            $e = new ErrorException($worker->error(), $worker->returnCode());
            // log exception
            break;
        }
    
        $worker->wait();
    }
    
    $worker->unregisterAll();
    

提交回复
热议问题