1. /**
  2. * Bootsmaps user data scripts for scheduled runs.
  3. *
  4. * @param {object} userData - An object containing script configurations.
  5. * Example: { script1: { path: '/scripts/script1.js', interval: '1h' }, script2: { path: '/scripts/script2.js', interval: '30m' } }
  6. */
  7. function bootstrapUserScripts(userData) {
  8. if (!userData || typeof userData !== 'object') {
  9. console.warn("Invalid userData provided.");
  10. return;
  11. }
  12. for (const scriptName in userData) {
  13. if (userData.hasOwnProperty(scriptName)) {
  14. const scriptConfig = userData[scriptName];
  15. const scriptPath = scriptConfig.path;
  16. const interval = scriptConfig.interval;
  17. if (typeof scriptPath !== 'string' || !scriptPath) {
  18. console.warn(`Invalid script path for ${scriptName}. Skipping.`);
  19. continue;
  20. }
  21. if (typeof interval !== 'string' || !interval) {
  22. console.warn(`Invalid interval for ${scriptName}. Skipping.`);
  23. continue;
  24. }
  25. // Create a new script instance
  26. const script = new ScheduledScript(scriptPath, interval);
  27. script.start();
  28. }
  29. }
  30. }
  31. /**
  32. * Represents a scheduled script.
  33. * @param {string} path - The path to the script file.
  34. * @param {string} interval - The interval for running the script (e.g., '1h', '30m').
  35. */
  36. class ScheduledScript {
  37. constructor(path, interval) {
  38. this.path = path;
  39. this.interval = interval;
  40. this.timeoutId = null;
  41. }
  42. /**
  43. * Starts the scheduled script.
  44. */
  45. start() {
  46. this.timeoutId = setTimeout(() => {
  47. try {
  48. this.runScript();
  49. } catch (error) {
  50. console.error(`Error running script ${this.path}:`, error);
  51. } finally {
  52. this.start(); // Restart after execution.
  53. }
  54. }, this.getIntervalInMilliseconds());
  55. }
  56. /**
  57. * Executes the script.
  58. */
  59. runScript() {
  60. try {
  61. eval(this.path); // Execute the script
  62. } catch (error) {
  63. console.error(`Error executing script ${this.path}:`, error);
  64. }
  65. }
  66. /**
  67. * Converts interval string to milliseconds.
  68. * @returns {number} The interval in milliseconds.
  69. */
  70. getIntervalInMilliseconds() {
  71. const intervalRegex = /^(\d+)([hmns])/i;
  72. const match = this.interval.match(intervalRegex);
  73. if (!match) {
  74. console.warn(`Invalid interval format: ${this.interval}. Using default interval.`);
  75. return 60000; // Default to 1 minute
  76. }
  77. const minutes = parseInt(match[1], 10);
  78. const unit = match[3].toLowerCase();
  79. switch (unit) {
  80. case 'h':
  81. return minutes * 60 * 60 * 1000;
  82. case 'm':
  83. return minutes * 60 * 1000;
  84. case 's':
  85. return minutes * 1000;
  86. case 'n':
  87. case '': //handle no unit
  88. return 60000; // Default to 1 minute
  89. default:
  90. return 60000; // Default to 1 minute
  91. }
  92. }
  93. }

Add your comment