### Install CodeIgniter Queue Source: https://github.com/codeigniter4/queue/blob/develop/README.md Install the CodeIgniter Queue library using Composer. ```bash composer require codeigniter4/queue ``` -------------------------------- ### Job Handlers Example Source: https://github.com/codeigniter4/queue/blob/develop/docs/configuration.md Map job names to their corresponding class names, for example, associating 'email' with the Email::class. ```php public array $jobHandlers = [ 'email' => Email::class, ]; ``` -------------------------------- ### Queue Priorities Example Source: https://github.com/codeigniter4/queue/blob/develop/docs/configuration.md Define multiple priorities for jobs within a specific queue, like 'emails' supporting 'high' and 'low' priorities. ```php public array $queuePriorities = [ 'emails' => ['high', 'low'], ]; ``` -------------------------------- ### Default Queue Priority Example Source: https://github.com/codeigniter4/queue/blob/develop/docs/configuration.md Set a default priority for jobs added to a specific queue, such as 'emails' with 'low' priority. ```php public array $queueDefaultPriority = [ 'emails' => 'low', ]; ``` -------------------------------- ### Manually Add Queue Namespace to Autoloader Source: https://github.com/codeigniter4/queue/blob/develop/docs/installation.md For manual installation, add the 'CodeIgniter\Queue' namespace to the \$psr4 array in app/Config/Autoload.php, pointing to the library's source directory. ```php APPPATH, 'Config' => APPPATH . 'Config', 'CodeIgniter\Queue' => APPPATH . 'ThirdParty/queue/src', ]; // ... ``` -------------------------------- ### Run Queue Worker Source: https://github.com/codeigniter4/queue/blob/develop/README.md Start the queue worker process to execute jobs from a specified queue. ```bash php spark queue:work queueName ``` -------------------------------- ### Consume Jobs from a Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Starts a worker to process jobs from a specified queue. You can configure options like sleep time, maximum jobs, memory limits, and priority. ```bash php spark queue:work emails -max-jobs 5 ``` ```bash php spark queue:work emails -max-jobs 5 -priority low,high ``` -------------------------------- ### Accessing Event Metadata Source: https://github.com/codeigniter4/queue/blob/develop/docs/events.md Retrieve specific metadata values by key or get all metadata associated with the event. ```php // Get specific metadata $event->getMetadata('worker_id'); $event->getMetadata('priority', 'default'); // Get all metadata $metadata = $event->getAllMetadata(); ``` -------------------------------- ### Migrate Database for Queue Source: https://github.com/codeigniter4/queue/blob/develop/README.md Run database migrations to set up the necessary tables for the queue system. ```bash php spark migrate --all ``` -------------------------------- ### Publish Queue Configuration Source: https://github.com/codeigniter4/queue/blob/develop/README.md Publish the queue configuration file to your application's config directory. ```bash php spark queue:publish ``` -------------------------------- ### Registering Queue Event Listeners Source: https://github.com/codeigniter4/queue/blob/develop/docs/events.md Add these listeners in `app/Config/Events.php` to react to job completion, failures, and worker lifecycle changes. ```php $event->getJobClass(), 'time' => $event->getProcessingTime(), ]); }); // Listen to job failures Events::on(QueueEventManager::JOB_FAILED, static function (QueueEvent $event) { log_message('error', 'Job failed: {job} - {error}', [ 'job' => $event->getJobClass(), 'error' => $event->getExceptionMessage(), ]); }); // Listen to worker lifecycle Events::on(QueueEventManager::WORKER_STARTED, static function (QueueEvent $event) { log_message('info', 'Worker started for queue: {queue}', [ 'queue' => $event->getQueue(), ]); }); Events::on(QueueEventManager::WORKER_STOPPED, static function (QueueEvent $event) { $metadata = $event->getAllMetadata(); log_message('info', 'Worker stopped: {reason}, processed {jobs} jobs in {time}s', [ 'reason' => $metadata['stop_reason'], 'jobs' => $metadata['jobs_processed'], 'time' => round($metadata['uptime_seconds'], 2), ]); }); ``` -------------------------------- ### Configure Job Handlers in Queue.php Source: https://github.com/codeigniter4/queue/blob/develop/docs/basic-usage.md Add your custom job classes to the `$jobHandlers` array in `app/Config/Queue.php` to register them with the queue system. ```php // app/Config/Queue.php use App\Jobs\Email; // ... /** * Your jobs handlers. */ public array $jobHandlers = [ 'email' => Email::class, ]; // ... ``` -------------------------------- ### Implement a Basic Email Job Source: https://github.com/codeigniter4/queue/blob/develop/docs/basic-usage.md Define the `process` method within your job class to contain the logic for sending an email. The `$this->data` variable holds any data passed to the job. ```php setTo('test@email.test') ->setSubject('My test email') ->setMessage($this->data['message']) ->send(false); if (! $result) { throw new Exception($email->printDebugger('headers')); } return $result; } } ``` -------------------------------- ### Create a New Job Source: https://github.com/codeigniter4/queue/blob/develop/README.md Generate a new job class using the spark command. ```bash php spark queue:job Example ``` -------------------------------- ### Generate New Job File Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Creates a new job class file. Specify the desired class name. You can also set a custom namespace or append a suffix to the class name. ```bash php spark queue:job Email ``` -------------------------------- ### Push a Job to the Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/basic-usage.md Use the `push` method to send a single job to a specified queue with optional parameters. The method returns a `QueuePushResult` object. ```php service('queue')->push('queueName', 'jobName', ['array' => 'parameters']); ``` ```php service('queue')->push('emails', 'email', ['message' => 'Email message goes here']); ``` -------------------------------- ### Configure Job Retry Options Source: https://github.com/codeigniter4/queue/blob/develop/docs/basic-usage.md Set the `$retryAfter` and `$tries` properties in your job class to define how many times a job should be retried and the delay between retries. These are the default values. ```php // ... class Email extends BaseJob { protected int $retryAfter = 60; protected int $tries = 1; // ... } ``` -------------------------------- ### Accessing Basic Event Information Source: https://github.com/codeigniter4/queue/blob/develop/docs/events.md Retrieve fundamental details about the event, such as its type, handler, queue, and timestamp. ```php $event->getType(); // Event type (e.g., 'queue.job.pushed') $event->getHandler(); // Handler name (e.g., 'database', 'redis') $event->getQueue(); // Queue name (e.g., 'emails', 'default') $event->getTimestamp(); // Time object when event occurred ``` -------------------------------- ### Configure Job Handlers Source: https://github.com/codeigniter4/queue/blob/develop/README.md Add your custom job handler to the `app\Config\Queue.php` configuration file. This maps a job name to its corresponding class. ```php // ... use App\Jobs\Example; // ... public array $jobHandlers = [ 'my-example' => Example::class ]; // ... ``` -------------------------------- ### Add a Job to the Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/index.md Use this method to add a new job to a specified queue with associated parameters. Ensure the queue service is available. ```php service('queue')->push('queueName', 'jobName', ['array' => 'parameters']); ``` -------------------------------- ### Add Job to Queue Source: https://github.com/codeigniter4/queue/blob/develop/README.md Push a new job onto the queue with its name and associated data. The data can be any array. ```php service('queue')->push('queueName', 'my-example', ['data' => 'array']); ``` -------------------------------- ### Chained Push vs Regular Push Priority Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Illustrates the difference in setting priority for chained jobs versus regular queue jobs. For chained jobs, priority is set after `push()`; for regular jobs, it's set before. ```php // Regular push() - priority set before pushing service('queue')->setPriority('high')->push('queue', 'job', []); // Chain push() - priority set after pushing service('queue')->chain(function($chain) { $chain->push('queue', 'job', [])->setPriority('high'); }); ``` -------------------------------- ### Run Queue Worker with Supervisor Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Use this command to run a queue worker that continuously checks for new jobs. The wait time prevents excessive database queries when the queue is empty. ```bash php spark queue:work emails -wait 10 ``` -------------------------------- ### Push Chained Jobs to the Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/basic-usage.md Use the `chain` method to send multiple jobs that will be executed in sequence. Subsequent jobs only run if the preceding ones are successful. Returns a `QueuePushResult` object. ```php service('queue')->chain(function($chain) { $chain ->push('reports', 'generate-report', ['userId' => 123]) ->push('emails', 'email', ['message' => 'Email message goes here', 'userId' => 123]); }); ``` -------------------------------- ### Chaining Jobs in CodeIgniter Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Use the `chain()` method to define a sequence of jobs that will execute in order. Each job's configuration (priority, delay) must be set after its `push()` call. ```php service('queue')->chain(function($chain) { $chain ->push('reports', 'generate-report', ['userId' => 123]) ->setPriority('high') // optional ->push('emails', 'email', ['message' => 'Email message goes here', 'userId' => 123]) ->setDelay(30); // optional }); ``` -------------------------------- ### Configure Composer Minimum Stability Source: https://github.com/codeigniter4/queue/blob/develop/docs/installation.md If you encounter stability issues with Composer, update your project's minimum-stability setting to 'dev' and prefer stable packages. ```bash composer config minimum-stability dev composer config prefer-stable true ``` -------------------------------- ### Add Jobs with Specific Priorities Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Add jobs to the queue with either the default priority or a specified priority. The `setPriority` method allows for explicit priority setting before pushing a job. ```php // This job will have low priority: service('queue')->push('emails', 'email', ['message' => 'Email message with low priority']); // But this one will have high priority service('queue')->setPriority('high')->push('emails', 'email', ['message' => 'Email message with high priority']); ``` -------------------------------- ### Run Queue Worker with Specified Priority Order Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Execute the queue worker, overriding the default priority order defined in the configuration. Jobs will be consumed in the order specified in the command-line argument. ```bash php spark queue:work emails -priority low,high ``` -------------------------------- ### Add a Delayed Job to the Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Schedule a job to be executed after a specified delay. The delay is measured in seconds, and the job will not run before this time has elapsed. ```php // This job will be run not sooner than in 5 minutes service('queue')->setDelay(5 * MINUTE)->push('emails', 'email', ['message' => 'Email sent no sooner than 5 minutes from now']); ``` -------------------------------- ### Configure Default and Custom Queue Priorities Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md Define default and custom priority levels for queues. This configuration is used by the queue worker to process jobs in a specific order. ```php // app/Config/Queue.php public array $queueDefaultPriority = [ 'emails' => 'low', ]; public array $queuePriorities = [ 'emails' => ['high', 'low'], ]; ``` -------------------------------- ### View Failed Jobs Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Displays a list of all failed jobs. You can filter the results to show failed jobs from a specific queue. ```bash php spark queue:failed -queue emails ``` -------------------------------- ### Run Queue Worker with CRON Source: https://github.com/codeigniter4/queue/blob/develop/docs/running-queues.md This command is suitable for CRON jobs, processing a maximum number of jobs per execution and stopping when the queue is empty. This prevents resource overload during high traffic. ```bash php spark queue:work emails -max-jobs 20 --stop-when-empty ``` -------------------------------- ### Accessing Error Information for Failed Events Source: https://github.com/codeigniter4/queue/blob/develop/docs/events.md When an event signifies a job failure, retrieve the exception details and check if an error occurred. ```php $event->getException(); // Exception object (if any) $event->getExceptionMessage(); // Exception message $event->hasFailed(); // True if event contains an exception ``` -------------------------------- ### Retrieving Job Details Source: https://github.com/codeigniter4/queue/blob/develop/docs/events.md Access specific information related to a job when the event is job-related. ```php $event->getJobId(); // Job ID $event->getJobClass(); // Fully qualified job class name $event->getPriority(); // Job priority $event->getAttempts(); // Number of attempts $event->getStatus(); // Job status $event->getProcessingTime(); // Processing time in seconds $event->getProcessingTimeMs(); // Processing time in milliseconds ``` -------------------------------- ### Require Specific Queue Version via Composer Source: https://github.com/codeigniter4/queue/blob/develop/docs/installation.md Alternatively, specify an explicit version constraint for the queue package, such as the 'dev-develop' branch, to resolve stability issues. ```bash composer require codeigniter4/queue:dev-develop ``` -------------------------------- ### Checking Event Types Source: https://github.com/codeigniter4/queue/blob/develop/docs/events.md Determine the category of the event using boolean checks for job, worker, connection, or operation events. ```php $event->isJobEvent(); // True for job-related events $event->isWorkerEvent(); // True for worker-related events $event->isConnectionEvent(); // True for connection-related events $event->isOperationEvent(); // True for operation events ``` -------------------------------- ### Implement Job with Database Transactions Source: https://github.com/codeigniter4/queue/blob/develop/docs/basic-usage.md When using database transactions within a job, ensure Strict Mode is disabled for the connection to prevent issues with long-running processes. Rollback transactions if an exception occurs. ```php // ... class Email extends BaseJob { /** * @throws Exception */ public function process(string $data): { try { $db = db_connect(); // Disable Strict Mode $db->transStrict(false); $db->transBegin(); // Job logic goes here // Your code should throw an exception on error if ($db->transStatus() === false) { $db->transRollback(); } else { $db->transCommit(); } } catch (Exception $e) { $db->transRollback(); throw $e; } } } ``` -------------------------------- ### Retry Failed Jobs Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Re-queues failed jobs to be processed again. You can retry a specific job by its ID or retry all failed jobs for a given queue. ```bash php spark queue:retry all -queue emails ``` -------------------------------- ### Clear All Jobs from a Queue Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Removes all pending jobs from a specified queue. Use with caution as this action is irreversible. ```bash php spark queue:clear emails ``` -------------------------------- ### Delete Multiple Failed Jobs Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Deletes multiple failed jobs based on their age and queue. Specify the number of hours to retain failed jobs. ```bash php spark queue:flush -hours 6 ``` -------------------------------- ### Stop a Queue Safely Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Gracefully stops a queue worker after the current job is completed. This ensures no jobs are interrupted mid-process. ```bash php spark queue:stop emails ``` -------------------------------- ### Delete a Specific Failed Job Source: https://github.com/codeigniter4/queue/blob/develop/docs/commands.md Removes a single failed job from the system using its unique ID. This is useful for cleaning up individual failed job records. ```bash php spark queue:forget 123 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.