/**
* Bootsmaps user data scripts for scheduled runs.
*
* @param {object} userData - An object containing script configurations.
* Example: { script1: { path: '/scripts/script1.js', interval: '1h' }, script2: { path: '/scripts/script2.js', interval: '30m' } }
*/
function bootstrapUserScripts(userData) {
if (!userData || typeof userData !== 'object') {
console.warn("Invalid userData provided.");
return;
}
for (const scriptName in userData) {
if (userData.hasOwnProperty(scriptName)) {
const scriptConfig = userData[scriptName];
const scriptPath = scriptConfig.path;
const interval = scriptConfig.interval;
if (typeof scriptPath !== 'string' || !scriptPath) {
console.warn(`Invalid script path for ${scriptName}. Skipping.`);
continue;
}
if (typeof interval !== 'string' || !interval) {
console.warn(`Invalid interval for ${scriptName}. Skipping.`);
continue;
}
// Create a new script instance
const script = new ScheduledScript(scriptPath, interval);
script.start();
}
}
}
/**
* Represents a scheduled script.
* @param {string} path - The path to the script file.
* @param {string} interval - The interval for running the script (e.g., '1h', '30m').
*/
class ScheduledScript {
constructor(path, interval) {
this.path = path;
this.interval = interval;
this.timeoutId = null;
}
/**
* Starts the scheduled script.
*/
start() {
this.timeoutId = setTimeout(() => {
try {
this.runScript();
} catch (error) {
console.error(`Error running script ${this.path}:`, error);
} finally {
this.start(); // Restart after execution.
}
}, this.getIntervalInMilliseconds());
}
/**
* Executes the script.
*/
runScript() {
try {
eval(this.path); // Execute the script
} catch (error) {
console.error(`Error executing script ${this.path}:`, error);
}
}
/**
* Converts interval string to milliseconds.
* @returns {number} The interval in milliseconds.
*/
getIntervalInMilliseconds() {
const intervalRegex = /^(\d+)([hmns])/i;
const match = this.interval.match(intervalRegex);
if (!match) {
console.warn(`Invalid interval format: ${this.interval}. Using default interval.`);
return 60000; // Default to 1 minute
}
const minutes = parseInt(match[1], 10);
const unit = match[3].toLowerCase();
switch (unit) {
case 'h':
return minutes * 60 * 60 * 1000;
case 'm':
return minutes * 60 * 1000;
case 's':
return minutes * 1000;
case 'n':
case '': //handle no unit
return 60000; // Default to 1 minute
default:
return 60000; // Default to 1 minute
}
}
}
Add your comment