简体   繁体   English

如何在 Nestjs Bull 中一次执行预定义数量的作业

[英]How to execute predefined number of jobs at one time in Nestjs bull

I have 65 same named jobs to execute in one queue with 3 instances of consumers (A, B, C).我有 65 个同名作业在一个队列中执行,其中包含 3 个消费者实例(A、B、C)。 I want to do at one time each consumer execute 10 jobs.我想一次让每个消费者执行 10 个作业。 After the 10 execution completed, if there are available jobs greater than 10 in the queue that consumer again execute 10 jobs. 10 执行完成后,如果队列中有大于 10 的可用作业,则消费者再次执行 10 作业。 If not execute available jobs.如果不执行可用作业。

jobs 1 to 65工作 1 至 65

Consumer A execute 1 to 10 Consumer B execute 11 to 20 Consumer C execute 21 to 30消费者 A 执行 1 到 10 消费者 B 执行 11 到 20 消费者 C 执行 21 到 30

Lets take B, A, C finished the execution in order.让我们以 B、A、C 的顺序完成执行。 then然后

B - 31,32,33,.40 A - 41,42,43,.50 C - 51,52,53,.60 B - 31,32,33,.40 A - 41,42,43,.50 C - 51,52,53,.60

if C finish the execution first, C execute the remaining 5 jobs.如果 C 先完成执行,则 C 执行剩余的 5 个作业。 Please can I know are there any ways to achieve this.请我知道有什么方法可以实现这一目标。

producer制作人

@Injectable()
export class SampleQueueProducerService {
  constructor(@InjectQueue('sample-queue') private sampleQueue: Queue) {}

  async sendDataToJob(message: string) {
    await this.sampleQueue.add('job', { message });
  }
}

consumer消费者

@Processor('sample-queue')
export class SampleQueueConsumerService {
  @Process({ name: 'job' })
  async sampleJob(job: Job<any>) {
    console.log(job.data);
  }
}

all 3 consumers are same as above.所有 3 个消费者都与上述相同。

You can get x jobs using this functionality ( bull reference )您可以使用此功能获得 x 个工作( 牛市参考

However you don't have this exactly supported with NestJS但是,NestJS 并不完全支持此功能

What you can do is use @OnGlobalQueueWaiting() or @OnQueueWaiting() to get the waiting jobs, storing them in an array, once it reaches 10, you can send them to be processed.您可以做的是使用@OnGlobalQueueWaiting()@OnQueueWaiting()获取等待的作业,将它们存储在一个数组中,一旦达到10,您就可以发送它们进行处理。

Something like:就像是:

@OnGlobalQueueWaiting()
async onGlobalWaiting(jobId: number, result: any) {
  const job = await this.myQueue.getJob(jobId);
  this.jobArray.push(job)
  if (this.jobArray.length >= 10) {
       await this.processJobs(this.jobArray);
       this.jobArray = [];
   }
}

async processJobs(jobs: Job[]){'
   jobs.forEach(job => do something)
}
 
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM