PHP code example of lekoala / kaly-tasks

1. Go to this page and download the library: Download lekoala/kaly-tasks library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lekoala / kaly-tasks example snippets


$this->tasks->dispatch(new GeneratePdf($documentId));

final readonly class GeneratePdf
{
    public function __construct(
        public string $documentId,
    ) {}

    public function __invoke(PdfGenerator $generator): void
    {
        $generator->generate($this->documentId);
    }
}

$tasks->dispatch(new DeliverSms($deliveryId), notBefore: $clock->now()->modify('+10 seconds'));
$tasks->dispatch(new SendReminder($appointmentId), notBefore: $reminderDate);

final readonly class SendAppointmentReminder
{
    public function __construct(
        public string $appointmentId,
        public int $version,
        public string $deduplicationKey,
    ) {}

    public function __invoke(AppointmentRepository $appointments, ReminderSender $sender): void
    {
        $appointment = $appointments->find($this->appointmentId);
        if ($appointment === null || $appointment->cancelled) {
            return;
        }
        if ($appointment->version !== $this->version) {
            return; // superseded by a later change
        }
        $sender->send($appointment);
    }
}

$registry->register(
    'appointments.remind',
    SendAppointmentReminder::class,
    deduplicateBy: 'deduplicationKey',
);

// On booking or rescheduling, ideally in the same application transaction:
$tasks->dispatch(
    new SendAppointmentReminder(
        $appointment->id,
        $appointment->version,
        "{$appointment->id}:{$appointment->version}",
    ),
    notBefore: $appointment->startsAt->modify('-1 day'),
);

$registry->register('reports.daily', GenerateDailyReport::class, deduplicateBy: 'period');

// On every host, from cron
$tasks->dispatch(new GenerateDailyReport($clock->now()->format('Y-m-d')));

$tasks->sequence([
    new PrepareConversation($id),
    new GenerateAnswer($id),
    new PublishAnswer($id),
], notBefore: $at);

$json = TaskChain::encode($encodedTask->chain); // string, or null for no continuation
$remaining = TaskChain::decode($json);         // list<EncodedTask>

$pdo = new PDO($writerDsn, $user, $password);
$store = new MysqlTaskStore(new PdoConnection($pdo));

foreach ($store->schema() as $statement) {
    // execute $statement
}

use Kaly\Task\ScheduledTaskDispatcher;
use Kaly\Task\TaskDispatcher;
use Kaly\Tasks\Connection\DoctrineConnection;
use Kaly\Tasks\DatabaseTaskDispatcher;
use Kaly\Tasks\RetryPolicy;
use Kaly\Tasks\Store\PostgresTaskStore;
use Kaly\Tasks\TaskRegistry;
use Kaly\Tasks\TaskSequenceDispatcher;

$app->configure(fn(Definitions $di) => $di
    ->set(TaskRegistry::class, static fn() => (new TaskRegistry())
        ->register('documents.generate-pdf', GeneratePdf::class)
        ->register('support.process-webhook', ProcessWebhook::class,
            queue: 'support',
            retry: new RetryPolicy(maxAttempts: 8, delay: 30),
            deduplicateBy: 'eventId',
        ))
    ->set(ScheduledTaskDispatcher::class, static fn(ContainerInterface $c) => new DatabaseTaskDispatcher(
        new PostgresTaskStore(new DoctrineConnection($c->get(EntityManagerInterface::class)->getConnection())),
        $c->get(TaskRegistry::class),
    ))
    ->alias(TaskDispatcher::class, ScheduledTaskDispatcher::class)
    ->alias(TaskSequenceDispatcher::class, ScheduledTaskDispatcher::class));

// bin/worker.php
$app = App::create(dirname(__DIR__))->boot();
$container = $app->container();

$worker = new Worker(
    new PostgresTaskStore(new PdoConnection(new PDO($queueDsn))),
    $container->get(TaskRegistry::class),
    $container->get(Injector::class)->invoke(...),
    $container->get(LoggerInterface::class),
);
$worker->run(new WorkerOptions(queues: ['default', 'support']));

$worker->run(new WorkerOptions(
    queues: ['delivery', 'async'],
    prioritizeQueues: true,
));

use Kaly\Tasks\Store\PostgresNotifyWaiter;

$store = new PostgresTaskStore(new PdoConnection(new PDO($queueDsn)));
$waiter = PostgresNotifyWaiter::fromDsn($store, $queueDsn);

$worker = new Worker(
    $store,
    $container->get(TaskRegistry::class),
    $container->get(Injector::class)->invoke(...),
    $container->get(LoggerInterface::class),
    waiter: $waiter,
);

foreach ($store->notificationSchema() as $statement) {
    // execute $statement
}

use Kaly\Tasks\PermanentFailure;
use Kaly\Tasks\RetryLater;

public function __invoke(SmsGateway $gateway): void
{
    try {
        $gateway->send($this->deliveryId);
    } catch (InvalidNumber $e) {
        throw new PermanentFailure($e->getMessage(), previous: $e);
    } catch (RateLimited $e) {
        throw new RetryLater($e->retryAfterSeconds, $e->getMessage(), $e);
    }
}

use Closure;
use Kaly\Tasks\TaskRun;

$worker = new Worker($store, $registry, $injector->invoke(...), $logger,
    around: static function (TaskRun $run, Closure $next) use ($logContext): void {
        $logContext->push(['task_id' => $run->id, 'task' => $run->name, 'attempt' => $run->attempt]);
        try {
            $next();
        } finally {
            $logContext->pop();
        }
    },
);

// bin/tasks-purge.php, daily from cron or a systemd timer
$store->purge(
    olderThanSeconds: 7 * 86400,
    failedOlderThanSeconds: null, // keep failed tasks until reviewed
);

  // bin/worker-exports.php
  $worker->run(new WorkerOptions(queues: ['exports'], lease: 3900, timeout: 3600));
  

$store->failed(limit: 50);        // inspect failed tasks
$store->deleteFailed($id);        // delete a failed task and free its deduplication key
$store->retryFailed($id);         // run a failed task again, with fresh attempts
$store->purge(7 * 24 * 3600, 30 * 24 * 3600); // delete done tasks after a week, failed ones after a month

$stats = $store->stats();           // whole table
$mailStats = $store->stats('mail'); // one queue

$stats->ready;              // pending, due now
$stats->scheduled;          // pending, due later, retries