PHP code example of philiprehberger / php-background-jobs
1. Go to this page and download the library: Download philiprehberger/php-background-jobs 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/ */
philiprehberger / php-background-jobs example snippets
use PhilipRehberger\BackgroundJobs\Contracts\Job;
class SendEmailJob implements Job
{
public function __construct(
private readonly string $to,
private readonly string $subject,
) {}
public function handle(): void
{
// Send the email...
}
}
use PhilipRehberger\BackgroundJobs\Drivers\FileDriver;
use PhilipRehberger\BackgroundJobs\Queue;
$driver = new FileDriver('/path/to/storage/queue');
$queue = new Queue($driver);
// Push a job for immediate processing
$id = $queue->push(new SendEmailJob('[email protected]', 'Welcome!'));
// Push a job with a delay (in seconds)
$id = $queue->later(new SendEmailJob('[email protected]', 'Reminder'), 3600);
use PhilipRehberger\BackgroundJobs\Worker;
// Process the next available job
$processed = Worker::processNext($queue);
// Process with a custom max attempts limit
$processed = Worker::processNext($queue, maxAttempts: 5);
// Get the number of pending jobs
$count = $queue->size();
// Clear all jobs
$queue->clear();
// Pop a job manually
$payload = $queue->pop();
if ($payload !== null) {
$job = $payload->resolveJob();
$job->handle();
}
use PhilipRehberger\BackgroundJobs\Contracts\QueueDriver;
use PhilipRehberger\BackgroundJobs\JobPayload;
class RedisDriver implements QueueDriver
{
public function push(JobPayload $payload): void { /* ... */ }
public function pop(): ?JobPayload { /* ... */ }
public function size(): int { /* ... */ }
public function clear(): void { /* ... */ }
}
use PhilipRehberger\BackgroundJobs\BaseJob;
class SendEmailJob extends BaseJob
{
public function __construct(
private readonly string $to,
) {}
public function handle(): void
{
// Send the email...
}
}
$job = new SendEmailJob('[email protected]');
$job->onSuccess(function ($job) {
echo "Job completed after {$job->getAttempts()} attempt(s).";
});
$job->onFailure(function ($job, \Throwable $e) {
echo "Job failed: {$e->getMessage()}";
});
$queue->push($job);
use PhilipRehberger\BackgroundJobs\Exceptions\JobFailedException;
try {
Worker::processNext($queue);
} catch (JobFailedException $e) {
echo $e->getMessage();
echo $e->payload->id; // Job ID
echo $e->payload->jobClass; // Original job class
echo $e->payload->attempts; // Number of attempts
}
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.