const schedule = require('node-schedule');
const fs = require('fs');
const path = require('path');
class FileScheduler {
constructor(rateLimit = 5, intervalSeconds = 60) {
this.rateLimit = rateLimit; // Max files to run per interval
this.intervalSeconds = intervalSeconds; // Interval between scheduling checks
this.scheduledFiles = [];
}
/**
* Schedules a file for execution with rate limiting.
* @param {string} filePath - The path to the file to execute.
*/
scheduleFile(filePath) {
// Check if the file is already scheduled
if (this.scheduledFiles.includes(filePath)) {
console.log(`File ${filePath} already scheduled.`);
return;
}
// Check rate limit
if (this.scheduledFiles.length >= this.rateLimit) {
console.log(`Rate limit reached. Cannot schedule ${filePath}.`);
return;
}
// Schedule the file
const job = schedule.scheduleJob(this.intervalSeconds, async () => {
try {
console.log(`Executing ${filePath} at ${new Date().toLocaleTimeString()}`);
await this.executeFile(filePath);
} catch (error) {
console.error(`Error executing ${filePath}:`, error);
}
});
this.scheduledFiles.push(filePath);
console.log(`Scheduled ${filePath} for execution.`);
}
/**
* Executes a file.
* @param {string} filePath - The path to the file to execute.
* @returns {Promise} - A promise that resolves when the file execution is complete.
*/
async executeFile(filePath) {
try {
// Read file content
const fileContent = fs.readFileSync(filePath, 'utf8');
// Execute the file content (e.g., using eval, but be cautious!)
// Consider using a safer execution method like vm (Node.js built-in) if possible.
eval(fileContent);
// Simulate some work
await new Promise(resolve => setTimeout(resolve, 1000));
} catch (error) {
throw error; // Re-throw the error for the scheduler to handle
}
}
/**
* Clears all scheduled files.
*/
clearSchedule() {
this.scheduledFiles = [];
this.scheduledJobs = schedule.getRules().filter(rule => rule.job.name === 'fileExecutor').map(rule => rule.job.id);
schedule.cancelJobs(this.scheduledJobs);
console.log('Schedule cleared.');
}
}
module.exports = FileScheduler;
Add your comment