How to Cancel or Stop a Job in Laravel

Before continuing with this tutorial or solution, we must mention that this solution works only for jobs stored in the database, but not for queues hosted on other services such as redis.

So, if you use the database to host your jobs, what you must do to cancel or stop a job is to obtain the job id and then delete it or defer the execution directly in the database.

If you don't know how to get the id, I recommend reading ┬┐How to get the ID of a job in Laravel?

Stop or Cancel a Job

If you want to stop a job to later run it again, you must change the execution time in seconds (available_at) as follows.

<?php namespace App\Services; use Carbon\Carbon; use Illuminate\Support\Facades\DB; class JobService { ... public int $cancel_years = 50; public function update_available_at(int $job_id, $callback_available_at) { $jobs_table = DB::table('jobs'); $job = $jobs_table->where('id', $job_id)->first(); $available_at = Carbon::createFromTimestamp($job->available_at); $jobs_table ->where('id', $job_id) ->update(['available_at' =>$callback_available_at($available_at)->timestamp]); } public function cancel(int $job_id) { $this->update_available_at($job_id, function ($available_at) { return $available_at->addYears($cancel_years); }); } public function resume(int $job_id) { $this->update_available_at($job_id, function ($available_at) { return $available_at->subYears($cancel_years); }); } }
Service to Cancel and Resume a Job

This will cause that the job will not run for up to 50 years, simulating that the job has been canceled or stopped so that changing the variable back to a current date in seconds would make it "available again" for execution.

As you can see, we are not canceling the job because this is currently not possible in Laravel but we are extending the execution time to 50 years so the job will not execute until then.

Delete a Job

On the other hand, if you want to delete the job, then you should delete it directly from the database using a query or the laravel query builder as follows.

<?php namespace App\Services; use Illuminate\Support\Facades\DB; class JobService { ... public function delete(int $job_id) { DB::table('jobs')->where('id', $job_id)->delete(); } }
Service to Delete a Job

Suggestions

If you want to have a better control of the jobs, I recommend you to save the ID in a column of your table or to relate them to a model through a belongsTo or belongsToMany relationship.