1. /**
  2. * Monitors a task queue for errors and handles them gracefully.
  3. *
  4. * @param {Array<Function>} taskQueue An array of functions representing tasks to be executed.
  5. * @param {number} concurrency The maximum number of tasks to run concurrently. Defaults to 1.
  6. * @param {number} interval The monitoring interval in milliseconds. Defaults to 1000.
  7. */
  8. async function monitorTaskQueue(taskQueue, concurrency = 1, interval = 1000) {
  9. let runningTasks = 0;
  10. const taskPromises = []; // Store promises for each running task
  11. /**
  12. * Executes a single task and handles errors.
  13. * @param {Function} task
  14. */
  15. async function executeTask(task) {
  16. try {
  17. await task();
  18. console.log("Task completed successfully.");
  19. } catch (error) {
  20. console.error("Task failed:", error);
  21. //Graceful handling: Log the error, potentially retry, or skip.
  22. } finally {
  23. runningTasks--;
  24. taskPromises.splice(taskPromises.indexOf(taskPromise), 1); //remove the taskPromise
  25. }
  26. }
  27. /**
  28. * Starts executing tasks based on concurrency.
  29. */
  30. async function startTasks() {
  31. for (let i = 0; i < concurrency && taskQueue.length > 0; i++) {
  32. const task = taskQueue.shift();
  33. runningTasks++;
  34. const taskPromise = executeTask(task);
  35. taskPromises.push(taskPromise);
  36. // Continue with the next task.
  37. if (taskQueue.length === 0) {
  38. await Promise.all(taskPromises); //wait for all tasks to complete.
  39. return;
  40. }
  41. }
  42. }
  43. //Initial start.
  44. startTasks();
  45. //Regular monitoring loop
  46. setInterval(async () => {
  47. if (runningTasks > 0) {
  48. //Check for pending tasks
  49. try {
  50. await Promise.race(taskPromises.map(p => p.then(async (res) => {
  51. return new Promise((resolve, reject) => {
  52. try {
  53. await res;
  54. resolve();
  55. } catch (err) {
  56. reject(err);
  57. }
  58. });
  59. })));
  60. //If all tasks completed, reset running tasks.
  61. runningTasks = 0;
  62. } catch (error){
  63. console.error("Error during monitoring:", error);
  64. }
  65. }
  66. }, interval);
  67. }

Add your comment