Skip to content

Properly Terminating a Background Job #119

@ronzyfonzy

Description

@ronzyfonzy

I have a worker that is executing multiple queues. Below is a simplified version of my code:

class JobTest extends BgJob
{

    public function perform($args)
    {
        parent::parseArgs($args);
        $this->_failLongRunningJobs("common-queue");
        // execute my job code
    }

    /** @param string $queue */
    private function _failLongRunningJobs($queue): void
    {
        $jobs_max_running_times = [
            "default"            => 7200,
            JobDeviceSync::class => 300,
            JobTest::class       => 60,
        ];

        /** @var \Resque\Job[] $running_jobs */
        $running_jobs = $this->_getQueueJobList($queue, "running");

        foreach ($running_jobs as $job) {
            $job_data = $job->getData();
            $started  = to_int(array_get($job_data, "started", 0));
            if (array_key_exists($job->getClass(), $jobs_max_running_times) and $started > 0) {
                $execution_time = time() - $started;
                $time_limit     = array_get($jobs_max_running_times, $job->getClass(), null);

                if ( ! is_null($time_limit) and $execution_time > $time_limit) {
                    $e = new Exception(
                        "Detected long running job {$job->getId()}. Running for {$execution_time} seconds."
                    );
                    $job->fail($e);
                }
            }
        }
    }
}

I've implemented a method _failLongRunningJobs() to check and fail long-running jobs, but this only updates the jobs data in Redis (the worker child process is still executing).

Is there a recommended way to safely interrupt and terminate a job that's currently being executed?

Thank you so much for the time invested in this project - it is much appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions