class TaskQueue {
constructor(tasks) {
this.tasks = tasks || []; // Array of tasks
this.queue = [...tasks]; // Create a copy for the queue
this.dryRun = true; // Default to dry-run mode
this.taskIndex = 0; // index of the current task
}
/**
* Adds a task to the queue.
* @param {Function} task The task to be added.
*/
addTask(task) {
this.queue.push(task);
}
/**
* Processes the next task in the queue.
*/
processTask() {
if (this.dryRun) {
console.log("Dry run: Would execute task at index:", this.taskIndex);
return;
}
if (this.taskIndex < this.queue.length) {
const task = this.queue[this.taskIndex];
console.log("Executing task:", this.taskIndex + 1); // log task index
try {
task(); // Execute the task
} catch (error) {
console.error("Error executing task:", error);
}
this.taskIndex++;
this.processTask(); // Process the next task
} else {
console.log("All tasks completed.");
}
}
/**
* Sets the dry-run mode.
* @param {boolean} dryRun True for dry-run, false for actual execution.
*/
setDryRun(dryRun) {
this.dryRun = dryRun;
}
/**
* Gets the current queue.
* @returns {Array<Function>} The current queue of tasks.
*/
getQueue() {
return [...this.queue]; // return a copy to prevent modification
}
}
// Example usage:
// const tasks = [
// () => console.log("Task 1: Performing maintenance"),
// () => console.log("Task 2: Checking system logs"),
// () => console.log("Task 3: Applying security patches"),
// ];
// const queue = new TaskQueue(tasks);
// queue.setDryRun(true); // Set to dry-run mode
// queue.processTask(); // Dry run output
// queue.setDryRun(false); // Set to actual execution mode
// queue.processTask(); // Execute tasks
Add your comment