Custom Job Types
A job type is the class Scheduler runs when a job's date arrives. Scheduler includes one job type, which re-saves an element. A custom job type lets you run your own code on a date, such as disabling an entry or sending a reminder, either from the Scheduler field or from your own PHP.
Create the Job Type Class
Extend verbb\scheduler\jobs\BaseSchedulerJob and implement run(). The job's Job model is available as $this->model, and its settings array holds whatever was stored when the job was scheduled. Jobs scheduled by the Scheduler field store the ID of the element being saved as elementId.
The following job type disables an element on the scheduled date.
<?php
namespace modules\sitemodule\jobs;
use Craft;
use verbb\scheduler\jobs\BaseSchedulerJob;
class DisableElementJob extends BaseSchedulerJob
{
public function run(): bool
{
$elementId = $this->model->settings['elementId'] ?? null;
$element = $elementId ? Craft::$app->getElements()->getElementById((int)$elementId) : null;
// The element no longer exists, so there's nothing left to do
if (!$element) {
return true;
}
$element->enabled = false;
return Craft::$app->getElements()->saveElement($element);
}
}Register the Job Type
Scheduler finds job types through the registerSchedulerJobTypes event. Register your class from your module or plugin’s init() method.
use modules\sitemodule\jobs\DisableElementJob;
use verbb\scheduler\events\RegisterSchedulerJobTypesEvent;
use verbb\scheduler\services\Jobs;
use yii\base\Event;
Event::on(Jobs::class, Jobs::EVENT_REGISTER_SCHEDULER_JOB_TYPES, function(RegisterSchedulerJobTypesEvent $event) {
$event->types[] = [
'label' => 'Disable element',
'value' => DisableElementJob::class,
];
});Each item needs a label, shown in the Job Type setting of the Scheduler field, and a value, which is the job type's class name.
Schedule a Job From PHP
Registering a job type makes it available to the Scheduler field. You can also schedule a job directly, with any job type class, using the jobs service.
use DateTime;
use modules\sitemodule\jobs\DisableElementJob;
use verbb\scheduler\Scheduler;
Scheduler::$plugin->getJobs()->addJob(DisableElementJob::class, new DateTime('+1 week'), 'programmatic', [
'elementId' => $entry->id,
]);addJob() takes the job type class, a DateTime for when the job should run, a context string and a settings array. When a job with the same type, context and settings already exists, Scheduler updates that job's date instead of adding another. A job whose date is more than a minute in the past isn't saved.
Methods
Returns whether the job ran successfully. The scheduler/command/run command deletes a job when this returns true. When it returns false, the job stays in place and runs again the next time the command runs.