# Cloudflare Workers with Swarms: Automated Cron Job Agents Deploy scheduled AI agents on Cloudflare's global edge network for automated stock analysis and healthcare monitoring. This guide focuses on cron job agents that run automatically at scheduled intervals. ## Overview Cloudflare Workers with cron triggers enable automated agent execution for: - **Stock Market Analysis**: Daily market reports and trading insights - **Healthcare Monitoring**: Patient data analysis and alerts - **Automated Reporting**: Scheduled business intelligence - **Global Deployment**: Edge computing with zero cold starts ## Quick Setup ### 1. Create Worker Project ```bash npx create-cloudflare stock-agent worker cd stock-agent ``` ### 2. Configure Cron Schedule Edit `wrangler.toml`: ```toml name = "stock-analysis-agent" main = "src/index.js" compatibility_date = "2024-01-01" [env.production.vars] SWARMS_API_KEY = "your-api-key-here" SLACK_WEBHOOK_URL = "optional-slack-webhook" # Stock market analysis - after market close [[env.production.triggers.crons]] cron = "0 21 * * MON-FRI" # 9 PM UTC (4 PM EST) # Healthcare monitoring - every 4 hours [[env.production.triggers.crons]] cron = "0 */4 * * *" ``` ## Stock Market Analysis Agent Automated daily stock analysis after market close: ```javascript export default { // Cron job handler - runs automatically async scheduled(event, env, ctx) { ctx.waitUntil(handleStockAnalysis(event, env)); } }; async function handleStockAnalysis(event, env) { try { // Step 1: Fetch real market data from multiple sources const marketData = await fetchMarketData(env); // Step 2: Get market news const marketNews = await fetchMarketNews(env); // Step 3: Send real data to Swarms agents for analysis const swarmConfig = { name: "Real-Time Stock Analysis", description: "Live market data analysis with AI agents", agents: [ { agent_name: "Technical Analyst", system_prompt: `You are a professional technical analyst. Analyze the provided real market data: - Calculate key technical indicators (RSI, MACD, Moving Averages) - Identify support and resistance levels - Determine market trends and momentum - Provide trading signals and price targets Format your analysis professionally with specific price levels.`, model_name: "gpt-4o-mini", max_tokens: 3000, temperature: 0.2 }, { agent_name: "Fundamental Analyst", system_prompt: `You are a fundamental market analyst. Using the provided market news and data: - Analyze earnings impact and company fundamentals - Evaluate economic indicators and Fed policy effects - Assess sector rotation and market sentiment - Identify value opportunities and risks Provide investment recommendations with risk assessment.`, model_name: "gpt-4o-mini", max_tokens: 3000, temperature: 0.3 } ], swarm_type: "ConcurrentWorkflow", task: `Analyze the following real market data and news: MARKET DATA: ${JSON.stringify(marketData, null, 2)} MARKET NEWS: ${marketNews} Provide comprehensive analysis with: 1. Technical analysis with key levels 2. Fundamental analysis with catalysts 3. Trading recommendations 4. Risk assessment 5. Tomorrow's key levels to watch`, max_loops: 1 }; const response = await fetch('https://api.swarms.world/v1/swarm/completions', { method: 'POST', headers: { 'x-api-key': env.SWARMS_API_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify(swarmConfig) }); const result = await response.json(); if (response.ok) { console.log('✅ Real-time stock analysis completed'); console.log('💰 Cost:', result.metadata?.billing_info?.total_cost); // Send email directly await sendEmailReport(env, result.output, marketData); } } catch (error) { console.error('❌ Real-time stock analysis failed:', error); } } // Fetch real market data from Alpha Vantage API async function fetchMarketData(env) { const symbols = ['SPY', 'QQQ', 'AAPL', 'MSFT', 'TSLA', 'NVDA']; const marketData = {}; for (const symbol of symbols) { try { // Get daily prices const priceResponse = await fetch( `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${symbol}&apikey=${env.STOCK_API_KEY}` ); const priceData = await priceResponse.json(); // Get technical indicators (RSI) const rsiResponse = await fetch( `https://www.alphavantage.co/query?function=RSI&symbol=${symbol}&interval=daily&time_period=14&series_type=close&apikey=${env.STOCK_API_KEY}` ); const rsiData = await rsiResponse.json(); if (priceData['Time Series (Daily)'] && rsiData['Technical Analysis: RSI']) { const latestDate = Object.keys(priceData['Time Series (Daily)'])[0]; const latestPrice = priceData['Time Series (Daily)'][latestDate]; const latestRSI = Object.values(rsiData['Technical Analysis: RSI'])[0]; marketData[symbol] = { price: parseFloat(latestPrice['4. close']), open: parseFloat(latestPrice['1. open']), high: parseFloat(latestPrice['2. high']), low: parseFloat(latestPrice['3. low']), volume: parseInt(latestPrice['5. volume']), change: parseFloat(latestPrice['4. close']) - parseFloat(latestPrice['1. open']), change_percent: ((parseFloat(latestPrice['4. close']) - parseFloat(latestPrice['1. open'])) / parseFloat(latestPrice['1. open']) * 100).toFixed(2), rsi: parseFloat(latestRSI?.RSI || 50), date: latestDate }; } // Rate limiting - Alpha Vantage allows 5 requests per minute on free tier await new Promise(resolve => setTimeout(resolve, 12000)); } catch (error) { console.error(`Error fetching data for ${symbol}:`, error); marketData[symbol] = { error: 'Failed to fetch data' }; } } return marketData; } // Fetch market news from Financial Modeling Prep (free tier available) async function fetchMarketNews(env) { try { const newsResponse = await fetch( `https://financialmodelingprep.com/api/v3/stock_news?tickers=AAPL,MSFT,TSLA,NVDA&limit=10&apikey=${env.FMP_API_KEY || 'demo'}` ); const newsData = await newsResponse.json(); if (Array.isArray(newsData)) { return newsData.slice(0, 5).map(article => ({ title: article.title, text: article.text?.substring(0, 300) + '...', publishedDate: article.publishedDate, symbol: article.symbol, url: article.url })); } } catch (error) { console.error('Error fetching news:', error); } return "Market news temporarily unavailable"; } // Send email report using Mailgun API async function sendEmailReport(env, analysis, marketData) { // Extract key market movers for email subject const movers = Object.entries(marketData) .filter(([symbol, data]) => data.change_percent && Math.abs(parseFloat(data.change_percent)) > 2) .map(([symbol, data]) => `${symbol}: ${data.change_percent}%`) .join(', '); const emailSubject = `📊 Daily Stock Analysis - ${new Date().toLocaleDateString()}`; const emailBody = `
Date: ${new Date().toLocaleString()}
Key Market Movers: ${movers || 'Market stable'}
${analysis}
Symbol | Price | Change % | Volume | RSI |
---|---|---|---|---|
${symbol} | $${data.price?.toFixed(2) || 'N/A'} | ${data.change_percent}% | ${data.volume?.toLocaleString() || 'N/A'} | ${data.rsi?.toFixed(1) || 'N/A'} |
Generated by Swarms AI Agent System
`; // Send via Mailgun const formData = new FormData(); formData.append('from', `Stock Analysis AgentTimestamp: ${new Date().toLocaleString()}
Severity Level: ${severity.toUpperCase()}
${analysis}
⚠️ IMMEDIATE ATTENTION REQUIRED
' : ''}Generated by Swarms Healthcare Monitoring Agent
`; // Send email using Mailgun const formData = new FormData(); formData.append('from', `Healthcare Monitor