File size: 1,598 Bytes
36d488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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.');