Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delay between Jobs #81

Open
mado-bohsali opened this issue Jul 14, 2022 · 4 comments
Open

Delay between Jobs #81

mado-bohsali opened this issue Jul 14, 2022 · 4 comments

Comments

@mado-bohsali
Copy link

How do I set a delay between jobs in a queue?
My jobs represent API calls

@jessetane
Copy link
Owner

Use setTimeout to execute the job's callback / resolve the promise it returned

@PlanetIrata
Copy link

Hi Jesse, could you provide an example code ? I’d like to use ˋqueueˋ to send e-mails and need to throttle the process to not exceed 4 sendings per seconds. Thx.

@harveysanders
Copy link

@PlanetIrata I know this is a month old, but maybe it will be helpful to the next person.
As @jessetane stated, you can use setTimeout to delay the invocation of the job's callback. When q.concurrency === 1, the queue will run the next job after the current job's callback is called.

const q = queue({ concurrency: 1, autostart: true });

function sendThrottledEmail(email) {
  q.push((cb) => {
    _sendEmail(email);
    setTimeout(cb, 250);
  });
}

You can also use a Promise. If sendEmail fails, an error event with be emitted on q.

const q = queue({ concurrency: 1, autostart: true });

function sendThrottledEmail(email) {
  const delay = 1000 / 4;

  q.push(
    () =>
      new Promise((resolve, reject) => {
        _sendEmail(email)
          .then(() => setTimeout(resolve, delay))
          .catch((err) => setTimeout(() => reject(err), delay));
          // or fail immediately and run the next job
          // .catch(reject);
      })
  );
}

@Chamuelm
Copy link

Chamuelm commented Aug 30, 2022

Althugh the suggestions above may work - the right tool for your need will be a rate limiter / throttler, see this: https://www.npmjs.com/package/limiter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants