For any scheduled task we can directly use Laravel’s queue but what if that task needs to be modified in some way before it gets executed?
Laravel Scheduled Action package stores all the tasks that need to run on a future date & time and executes each only on the day when it is scheduled to run so that we get the chance to modify the task before it gets executed. It uses Laravel’s task scheduling to figure out & handle the tasks that need to be run for the current day at the specified time for that task and sends the task payload to a receiver class of your app (configurable). So how to perform the task is totally up to you.
How it works:
- This package creates one table
model_actions - Every task has 4 statuses
PENDINGFINISHEDCANCELLEDDISPATCHED - The
scheduledaction:pollartisan command pollsPENDINGtasks for the present day and passes the tasks payload to your receiver class. - Set how often you want the poll to happen and how many tasks need to be passed to your receiver (the above example shows 10 per hour)
PENDINGtasks get to run at specified date & time, remember to mark the task asFINISHEDorCANCELLEDbased on how it was handled check the example.- Most likely you’ll use the
queueto run a task at a specified time so after dispatching to a queued job you might want to set the status asDISPATCHED.
Installation
composer require devsrv/laravel-scheduled-action
Setup
Now publish migrations by this command:
php artisan vendor:publish --provider="Devsrv\ScheduledAction\ScheduledActionServiceProvider" --tag="migrations"
Next, You’ve to run migrations:
php artisan migrate
Then you can publish the config file by this command:
php artisan vendor:publish --provider="Devsrv\ScheduledAction\ScheduledActionServiceProvider" --tag="config"
// the class that takes care of how to perform the task, the payload will be passed to this invokable class
return [
'receiver' => \App\Http\AutoAction\ScheduledActionReceiver::class, ? needs to be invokable
];
Add Scheduled Task to app/Console/Kernel.php
$schedule->command('scheduledaction:poll --tasks=10')->hourly(); // poll pending tasks (10 tasks every hour & sends payload to your receiver, customize as per your app)
Use the HasScheduledAction trait in your models
use Devsrv\ScheduledAction\Traits\HasScheduledAction;
class Candidate extends Model
{
use HasFactory, HasScheduledAction;
}
There are many fluent methods to interact with the scheduled action like:
- Get
- Create
- Update
This package has detailed code examples of these actions. If you wanna dig more, you can visit its complete documentation and source code on Github.