|
| 1 | +import { |
| 2 | + createScheduledJob, |
| 3 | + getScheduledJobs, |
| 4 | + getScheduledJob, |
| 5 | + updateScheduledJob, |
| 6 | + deleteScheduledJob, |
| 7 | + pauseScheduledJob, |
| 8 | + resumeScheduledJob, |
| 9 | + triggerScheduledJob, |
| 10 | + getJobExecutions, |
| 11 | + enableMock, |
| 12 | + disableMock |
| 13 | +} from '../index.js'; |
| 14 | + |
| 15 | +// Enable mock mode for testing |
| 16 | +enableMock(); |
| 17 | + |
| 18 | +/** |
| 19 | + * Create a SmartScraper scheduled job |
| 20 | + */ |
| 21 | +async function createSmartScraperJob(apiKey) { |
| 22 | + console.log('📅 Creating SmartScraper scheduled job...'); |
| 23 | + |
| 24 | + const jobConfig = { |
| 25 | + website_url: 'https://news.ycombinator.com', |
| 26 | + user_prompt: 'Extract the top 5 news titles and their URLs', |
| 27 | + render_heavy_js: false, |
| 28 | + headers: { |
| 29 | + 'User-Agent': 'Mozilla/5.0 (compatible; ScheduledJob/1.0)' |
| 30 | + } |
| 31 | + }; |
| 32 | + |
| 33 | + try { |
| 34 | + const result = await createScheduledJob( |
| 35 | + apiKey, |
| 36 | + 'HN Top News Scraper', |
| 37 | + 'smartscraper', |
| 38 | + '0 */6 * * *', // Every 6 hours |
| 39 | + jobConfig, |
| 40 | + true |
| 41 | + ); |
| 42 | + |
| 43 | + console.log(`✅ Created SmartScraper job with ID: ${result.id}`); |
| 44 | + return result.id; |
| 45 | + } catch (error) { |
| 46 | + console.error('❌ Error creating SmartScraper job:', error.message); |
| 47 | + throw error; |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Create a SearchScraper scheduled job |
| 53 | + */ |
| 54 | +async function createSearchScraperJob(apiKey) { |
| 55 | + console.log('📅 Creating SearchScraper scheduled job...'); |
| 56 | + |
| 57 | + const jobConfig = { |
| 58 | + user_prompt: 'Find the latest AI and machine learning news', |
| 59 | + num_results: 5, |
| 60 | + headers: { |
| 61 | + 'User-Agent': 'Mozilla/5.0 (compatible; ScheduledJob/1.0)' |
| 62 | + } |
| 63 | + }; |
| 64 | + |
| 65 | + try { |
| 66 | + const result = await createScheduledJob( |
| 67 | + apiKey, |
| 68 | + 'AI News Search', |
| 69 | + 'searchscraper', |
| 70 | + '0 9 * * 1', // Every Monday at 9 AM |
| 71 | + jobConfig, |
| 72 | + true |
| 73 | + ); |
| 74 | + |
| 75 | + console.log(`✅ Created SearchScraper job with ID: ${result.id}`); |
| 76 | + return result.id; |
| 77 | + } catch (error) { |
| 78 | + console.error('❌ Error creating SearchScraper job:', error.message); |
| 79 | + throw error; |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +/** |
| 84 | + * Create a Crawl scheduled job |
| 85 | + */ |
| 86 | +async function createCrawlJob(apiKey) { |
| 87 | + console.log('📅 Creating Crawl scheduled job...'); |
| 88 | + |
| 89 | + const jobConfig = { |
| 90 | + url: 'https://example.com', |
| 91 | + prompt: 'Extract all product information', |
| 92 | + extraction_mode: true, |
| 93 | + depth: 2, |
| 94 | + max_pages: 10, |
| 95 | + same_domain_only: true, |
| 96 | + cache_website: true |
| 97 | + }; |
| 98 | + |
| 99 | + try { |
| 100 | + const result = await createScheduledJob( |
| 101 | + apiKey, |
| 102 | + 'Product Catalog Crawler', |
| 103 | + 'crawl', |
| 104 | + '0 2 * * *', // Daily at 2 AM |
| 105 | + jobConfig, |
| 106 | + true |
| 107 | + ); |
| 108 | + |
| 109 | + console.log(`✅ Created Crawl job with ID: ${result.id}`); |
| 110 | + return result.id; |
| 111 | + } catch (error) { |
| 112 | + console.error('❌ Error creating Crawl job:', error.message); |
| 113 | + throw error; |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +/** |
| 118 | + * Manage scheduled jobs |
| 119 | + */ |
| 120 | +async function manageJobs(apiKey, jobIds) { |
| 121 | + console.log('\n🔧 Managing scheduled jobs...'); |
| 122 | + |
| 123 | + try { |
| 124 | + // List all jobs |
| 125 | + console.log('\n📋 Listing all scheduled jobs:'); |
| 126 | + const jobsResult = await getScheduledJobs(apiKey, { page: 1, pageSize: 10 }); |
| 127 | + console.log(`Total jobs: ${jobsResult.total}`); |
| 128 | + |
| 129 | + jobsResult.jobs.forEach(job => { |
| 130 | + console.log(` - ${job.job_name} (${job.service_type}) - Active: ${job.is_active}`); |
| 131 | + }); |
| 132 | + |
| 133 | + // Get details of first job |
| 134 | + if (jobIds.length > 0) { |
| 135 | + console.log(`\n🔍 Getting details for job ${jobIds[0]}:`); |
| 136 | + const jobDetails = await getScheduledJob(apiKey, jobIds[0]); |
| 137 | + console.log(` Name: ${jobDetails.job_name}`); |
| 138 | + console.log(` Cron: ${jobDetails.cron_expression}`); |
| 139 | + console.log(` Next run: ${jobDetails.next_run_at || 'N/A'}`); |
| 140 | + |
| 141 | + // Pause the first job |
| 142 | + console.log(`\n⏸️ Pausing job ${jobIds[0]}:`); |
| 143 | + const pauseResult = await pauseScheduledJob(apiKey, jobIds[0]); |
| 144 | + console.log(` Status: ${pauseResult.message}`); |
| 145 | + |
| 146 | + // Resume the job |
| 147 | + console.log(`\n▶️ Resuming job ${jobIds[0]}:`); |
| 148 | + const resumeResult = await resumeScheduledJob(apiKey, jobIds[0]); |
| 149 | + console.log(` Status: ${resumeResult.message}`); |
| 150 | + |
| 151 | + // Update job configuration |
| 152 | + console.log(`\n📝 Updating job ${jobIds[0]}:`); |
| 153 | + const updateResult = await updateScheduledJob(apiKey, jobIds[0], { |
| 154 | + jobName: 'Updated HN News Scraper', |
| 155 | + cronExpression: '0 */4 * * *' // Every 4 hours instead of 6 |
| 156 | + }); |
| 157 | + console.log(` Updated job name: ${updateResult.job_name}`); |
| 158 | + console.log(` Updated cron: ${updateResult.cron_expression}`); |
| 159 | + } |
| 160 | + } catch (error) { |
| 161 | + console.error('❌ Error managing jobs:', error.message); |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * Trigger and monitor jobs |
| 167 | + */ |
| 168 | +async function triggerAndMonitorJobs(apiKey, jobIds) { |
| 169 | + console.log('\n🚀 Triggering and monitoring jobs...'); |
| 170 | + |
| 171 | + for (const jobId of jobIds) { |
| 172 | + try { |
| 173 | + console.log(`\n🎯 Manually triggering job ${jobId}:`); |
| 174 | + const triggerResult = await triggerScheduledJob(apiKey, jobId); |
| 175 | + const executionId = triggerResult.execution_id; |
| 176 | + console.log(` Execution ID: ${executionId}`); |
| 177 | + console.log(` Message: ${triggerResult.message}`); |
| 178 | + |
| 179 | + // Wait a bit for execution to start |
| 180 | + await new Promise(resolve => setTimeout(resolve, 2000)); |
| 181 | + |
| 182 | + // Get execution history |
| 183 | + console.log(`\n📊 Getting execution history for job ${jobId}:`); |
| 184 | + const executions = await getJobExecutions(apiKey, jobId, { page: 1, pageSize: 5 }); |
| 185 | + console.log(` Total executions: ${executions.total}`); |
| 186 | + |
| 187 | + executions.executions.slice(0, 3).forEach(execution => { |
| 188 | + console.log(` - Execution ${execution.id}: ${execution.status}`); |
| 189 | + console.log(` Started: ${execution.started_at}`); |
| 190 | + if (execution.completed_at) { |
| 191 | + console.log(` Completed: ${execution.completed_at}`); |
| 192 | + } |
| 193 | + if (execution.credits_used) { |
| 194 | + console.log(` Credits used: ${execution.credits_used}`); |
| 195 | + } |
| 196 | + }); |
| 197 | + } catch (error) { |
| 198 | + console.error(`❌ Error triggering job ${jobId}:`, error.message); |
| 199 | + } |
| 200 | + } |
| 201 | +} |
| 202 | + |
| 203 | +/** |
| 204 | + * Clean up created jobs |
| 205 | + */ |
| 206 | +async function cleanupJobs(apiKey, jobIds) { |
| 207 | + console.log('\n🧹 Cleaning up created jobs...'); |
| 208 | + |
| 209 | + for (const jobId of jobIds) { |
| 210 | + try { |
| 211 | + console.log(`🗑️ Deleting job ${jobId}:`); |
| 212 | + const deleteResult = await deleteScheduledJob(apiKey, jobId); |
| 213 | + console.log(` Status: ${deleteResult.message}`); |
| 214 | + } catch (error) { |
| 215 | + console.error(`❌ Error deleting job ${jobId}:`, error.message); |
| 216 | + } |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +/** |
| 221 | + * Main function demonstrating scheduled jobs |
| 222 | + */ |
| 223 | +async function main() { |
| 224 | + const apiKey = process.env.SGAI_API_KEY || 'your-api-key-here'; |
| 225 | + |
| 226 | + if (apiKey === 'your-api-key-here') { |
| 227 | + console.log('❌ Error: SGAI_API_KEY environment variable not set'); |
| 228 | + console.log('Please either:'); |
| 229 | + console.log(' 1. Set environment variable: export SGAI_API_KEY="your-api-key-here"'); |
| 230 | + console.log(' 2. Or update the apiKey variable in this script'); |
| 231 | + return; |
| 232 | + } |
| 233 | + |
| 234 | + console.log('🚀 Starting Scheduled Jobs Demo'); |
| 235 | + console.log('='.repeat(50)); |
| 236 | + |
| 237 | + const jobIds = []; |
| 238 | + |
| 239 | + try { |
| 240 | + // Create different types of scheduled jobs |
| 241 | + const smartscraperJobId = await createSmartScraperJob(apiKey); |
| 242 | + jobIds.push(smartscraperJobId); |
| 243 | + |
| 244 | + const searchscraperJobId = await createSearchScraperJob(apiKey); |
| 245 | + jobIds.push(searchscraperJobId); |
| 246 | + |
| 247 | + const crawlJobId = await createCrawlJob(apiKey); |
| 248 | + jobIds.push(crawlJobId); |
| 249 | + |
| 250 | + // Manage jobs |
| 251 | + await manageJobs(apiKey, jobIds); |
| 252 | + |
| 253 | + // Trigger and monitor jobs |
| 254 | + await triggerAndMonitorJobs(apiKey, jobIds); |
| 255 | + |
| 256 | + } catch (error) { |
| 257 | + console.error('❌ Error during execution:', error.message); |
| 258 | + } finally { |
| 259 | + // Clean up |
| 260 | + await cleanupJobs(apiKey, jobIds); |
| 261 | + } |
| 262 | + |
| 263 | + console.log('\n✅ Scheduled Jobs Demo completed!'); |
| 264 | +} |
| 265 | + |
| 266 | +// Run the demo |
| 267 | +main().catch(console.error); |
0 commit comments