Count jobs on Queue

Hello there,

I’m working yii2-queue with db; I use it to start OpenStack API calls in background. Some of these tasks could delay a few minutes, so I’m planning to use more than one queue.

In order to select the proper queue, I need to count the pendant jobs. How can I do it?

Thank you!

In case someone stumble upon the same issue and use DB queue, you can create a few channels at config:

'queue1' => [
            'class' => \yii\queue\db\Queue::class,
			'db' => 'db', // DB connection component or its config
			'tableName' => '{{%queue}}', // Table name
			'channel' => 'channel1', // Queue channel key
			'mutex' => \yii\mutex\FileMutex::class,
			'ttr' => 5 * 60, // Max time for job execution
			'attempts' => 3, // Max number of attempts
        ],
'queue2' => [
            'class' => \yii\queue\db\Queue::class,
			'db' => 'db',
			'tableName' => '{{%queue}}',
			'channel' => 'channel2', // Queue channel key
			'mutex' => \yii\mutex\FileMutex::class,
			'ttr' => 5 * 60,
			'attempts' => 3,
        ],
...

and add a scan function to select the least busy:

	function getLeastBusyQueue()
	{
		$uppermost = PHP_INT_MAX;

		foreach( range(1, 2) as $channel ) // Supposed two channels
		{
			$count = (new \yii\db\Query())
				->from('queue')
				->where( [ 'channel' => "channel{$channel}" ] )
				->groupBy( 'channel' )
				->orderBy('count(*) Desc' )
				->count();

			if( $count < $uppermost )
			{
				$selected = "queue{$channel}";
				$uppermost = $count;
			}
		}

		return( Yii::$app->$selected );
	}