youtube-auto-bot / utils /scheduler.js
Nathan
Security: Fresh clean migration to GitHub
36d488d
Raw History Blame Contribute Delete
1.6 kB
const cron = require('node-cron');
const { runDailyAutomation } = require('./autonomous-agent');
const db = require('./db');
/**
* 24/7 Precision SaaS Scheduler
* Runs every minute to check for exact user-scheduled times.
*/
console.log('🕒 [PRECISION SCHEDULER] SaaS Automation Scheduler Started.');
// Run every minute
cron.schedule('* * * * *', async () => {
const now = new Date();
// Format as HH:mm (e.g. "09:15", "18:00")
const currentTime = now.toLocaleTimeString('en-GB', {
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: 'UTC' // Standardizing on UTC
});
console.log(`🚀 [SCHEDULER] Checking for users scheduled at ${currentTime}...`);
try {
// Find channels where the current time is in their preferred_hours list
const { data: channels } = await db.from('channels')
.select('user_id')
.filter('preferred_hours', 'cs', `["${currentTime}"]`)
.eq('is_active', true);
if (channels && channels.length > 0) {
console.log(`📈 [SCHEDULER] Found ${channels.length} users scheduled for this minute.`);
for (const chan of channels) {
console.log(`🤖 [SCHEDULER] Starting production for User: ${chan.user_id}`);
runDailyAutomation(chan.user_id).catch(err => {
console.error(`❌ [SCHEDULER] Error for User ${chan.user_id}:`, err);
});
}
}
} catch (err) {
console.error('❌ [SCHEDULER] Database check failed:', err);
}
}, {
scheduled: true,
timezone: "UTC"
});
console.log('✅ Precision Scheduler is active and checking every minute.');