Handling long-running tasks synchronously in Yii2 can slow down your application. Yii2 Queue allows you to process tasks in the background, improving performance and user experience.
Yii2 provides an official yii2-queue extension. Install it using Composer:
composer require yiisoft/yii2-queueYii2 Queue supports multiple backends. Here’s how to set up a MySQL queue (you can replace it with Redis, RabbitMQ, etc.).
Edit your Yii2 configuration file (config/console.php for Basic Template or console/config/main.php for Advanced Template):
'components' => [
'queue' => [
'class' => \yii\queue\db\Queue::class,
'db' => 'db', // Database connection component
'tableName' => '{{%queue}}', // Table storing the queue
'channel' => 'default', // Queue channel
'mutex' => \yii\mutex\MysqlMutex::class, // Avoid race conditions
],
],Run migrations to create the queue table:
php yii queue/db/init
php yii migrateCreate a job class inside console/jobs/SendEmailJob.php:
namespace console\jobs;
use yii\base\BaseObject;
use yii\queue\JobInterface;
class SendEmailJob extends BaseObject implements JobInterface
{
public $email;
public function execute($queue)
{
\Yii::$app->mailer->compose()
->setTo($this->email)
->setFrom('admin@example.com')
->setSubject('Welcome Email')
->setTextBody('Thank you for signing up!')
->send();
echo "Email sent to {$this->email}\n";
}
}Add a job in your controller or service:
Yii::$app->queue->push(new \console\jobs\SendEmailJob([
'email' => 'user@example.com'
]));This does not execute the job immediately. It stores it in the queue to be processed later.
There are two ways to run queue workers:
You can set up a cron job to process the queue every minute by adding this command to crontab:
* * * * * php /path-to-your-project/yii queue/run --verbose=1This approach works well for low to medium traffic applications.
For high-volume queues, it's better to run the worker as a long-running process instead of running it every minute via cron. This can be achieved using Supervisor.
1. Install Supervisor:
sudo apt install supervisor2. Create a new Supervisor config file:
sudo nano /etc/supervisor/conf.d/yii2-queue.conf3. Add the following configuration:
[program:yii2-queue]
command=php /path-to-your-project/yii queue/listen
autostart=true
autorestart=true
stderr_logfile=/var/log/yii2-queue.err.log
stdout_logfile=/var/log/yii2-queue.out.log4. Reload Supervisor:
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start yii2-queueNow, the queue runs in the background without manual intervention!
| Feature | Cron Job | Supervisor |
|---|---|---|
| Job Execution Speed | Runs jobs every minute | Jobs run instantly |
| Performance | Can be slow for high-traffic apps | Best for high-volume processing |
| Reliability | May cause overlapping jobs | Automatically restarts on failures |
| Best For | Low to medium traffic | High-performance applications |
Conclusion:
If a job fails, Yii2 can retry it automatically:
Yii::$app->queue->push(new SendEmailJob([
'email' => 'user@example.com'
]), 5); // Retry 5 times before failing permanentlyView failed jobs:
php yii queue/infoManually retry failed jobs:
php yii queue/retry 10 // Retry job with ID 10Yii2 Queue makes background processing simple. Whether sending emails, processing payments, or running heavy computations, you can improve performance and scalability with background jobs.
Sign in to join the discussion and post comments.
Sign in