1. const schedule = require('node-schedule');
  2. const fs = require('fs');
  3. const path = require('path');
  4. class FileScheduler {
  5. constructor(rateLimit = 5, intervalSeconds = 60) {
  6. this.rateLimit = rateLimit; // Max files to run per interval
  7. this.intervalSeconds = intervalSeconds; // Interval between scheduling checks
  8. this.scheduledFiles = [];
  9. }
  10. /**
  11. * Schedules a file for execution with rate limiting.
  12. * @param {string} filePath - The path to the file to execute.
  13. */
  14. scheduleFile(filePath) {
  15. // Check if the file is already scheduled
  16. if (this.scheduledFiles.includes(filePath)) {
  17. console.log(`File ${filePath} already scheduled.`);
  18. return;
  19. }
  20. // Check rate limit
  21. if (this.scheduledFiles.length >= this.rateLimit) {
  22. console.log(`Rate limit reached. Cannot schedule ${filePath}.`);
  23. return;
  24. }
  25. // Schedule the file
  26. const job = schedule.scheduleJob(this.intervalSeconds, async () => {
  27. try {
  28. console.log(`Executing ${filePath} at ${new Date().toLocaleTimeString()}`);
  29. await this.executeFile(filePath);
  30. } catch (error) {
  31. console.error(`Error executing ${filePath}:`, error);
  32. }
  33. });
  34. this.scheduledFiles.push(filePath);
  35. console.log(`Scheduled ${filePath} for execution.`);
  36. }
  37. /**
  38. * Executes a file.
  39. * @param {string} filePath - The path to the file to execute.
  40. * @returns {Promise} - A promise that resolves when the file execution is complete.
  41. */
  42. async executeFile(filePath) {
  43. try {
  44. // Read file content
  45. const fileContent = fs.readFileSync(filePath, 'utf8');
  46. // Execute the file content (e.g., using eval, but be cautious!)
  47. // Consider using a safer execution method like vm (Node.js built-in) if possible.
  48. eval(fileContent);
  49. // Simulate some work
  50. await new Promise(resolve => setTimeout(resolve, 1000));
  51. } catch (error) {
  52. throw error; // Re-throw the error for the scheduler to handle
  53. }
  54. }
  55. /**
  56. * Clears all scheduled files.
  57. */
  58. clearSchedule() {
  59. this.scheduledFiles = [];
  60. this.scheduledJobs = schedule.getRules().filter(rule => rule.job.name === 'fileExecutor').map(rule => rule.job.id);
  61. schedule.cancelJobs(this.scheduledJobs);
  62. console.log('Schedule cleared.');
  63. }
  64. }
  65. module.exports = FileScheduler;

Add your comment