Support the ongoing development of Laravel.io →
posted 3 years ago
Queues

I'm looking for ways to pause a job whenever the Queue worker (daemon) receives the shutdown signal (SIGTERM). Specially in a long running job where I need the job to resume from the part it stopped instead of starting from beginning. Say for the below code, how can I pause & resume the queued job ??

I tried with the App::terminating, but it did not worked. Using the pcntl_signal doesn't works this way queue worker's own graceful shutdown gets broken.

Any help will be appreciated.

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class DummyJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $shouldStopJob = false;

    public function handle()
    {
        Log::info('Attempt: ' . $this->attempts());
        Log::info('MaxTrys: ' . $this->job->maxTries());
        Log::info('Timeout: ' . $this->job->timeout());

        $i = Cache::get('dummy.loop-no', 0);
        $done = 60;
        if ($i >= $done) {
            Log::info("No need to proceed!");
            return;
        }

        App::terminating(function () {
            Log::info('App Terminating');
            $this->shouldStopJob = true;
        });

        pcntl_signal(SIGTERM, function () {
            $this->shouldStopJob= true;
        });

        for (; $i < $done; $i++) {
            Log::info("Loop no. #{$i}");

            sleep(1);

            Cache::put('dummy.loop-no', $i, now()->addSeconds(60));

            if ($this->shouldStopJob) {
                Log::info("Stopping!");
                $this->job->release(10);
                break;
            }
        }

        if ($this->shouldStopJob) {
            return;
        }

        Log::info("Done!");
        Cache::forget('dummy.loop-no');
    }
}

Same thread at https://github.com/laravel/framework/discussions/38579q

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

a-h-abid a-h-abid Joined 17 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.