NAPISZ program (klasy) w php który będzie wysyłał emaile nie częściej niż jeden email na…
- User
NAPISZ program (klasy) w php który będzie wysyłał emaile nie częściej niż jeden email na 2 minuty. jeśli próba się nie powiedzie, to można wysłać email później. dozwolone są max 3 próby. zakładamy że mamy już mailer z metodą send(). wszystkie dane pobieramy z bazy danych
Assistant
Oto implementacja systemu wysyłania emaili z ograniczeniami czasowymi i liczbą prób:
<?php class EmailQueue { private $db; private $mailer; private const MAX_ATTEMPTS = 3; private const DELAY_MINUTES = 2; public function __construct($database, $mailer) { $this->db = $database; $this->mailer = $mailer; } /** * Dodaje email do kolejki */ public function addEmail($to, $subject, $body, $priority = 1) { $stmt = $this->db->prepare(" INSERT INTO email_queue (recipient, subject, body, priority, created_at, status) VALUES (?, ?, ?, ?, NOW(), 'pending') "); return $stmt->execute([$to, $subject, $body, $priority]); } /** * Przetwarza kolejkę emaili */ public function processQueue() { // Sprawdź czy można wysłać email (czy minęły 2 minuty od ostatniego) if (!$this->canSendEmail()) { return false; } // Pobierz następny email do wysłania $email = $this->getNextEmail(); if (!$email) { return false; } return $this->sendEmail($email); } /** * Sprawdza czy można wysłać email (ograniczenie czasowe) */ private function canSendEmail() { $stmt = $this->db->prepare(" SELECT last_sent_at FROM email_settings WHERE id = 1 "); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); if (!$result || !$result['last_sent_at']) { return true; } $lastSent = new DateTime($result['last_sent_at']); $now = new DateTime(); $diff = $now->diff($lastSent); return ($diff->i >= self::DELAY_MINUTES || $diff->h > 0 || $diff->days > 0); } /** * Pobiera następny email z kolejki */ private function getNextEmail() { $stmt = $this->db->prepare(" SELECT * FROM email_queue WHERE status = 'pending' AND attempts < ? AND (next_attempt_at IS NULL OR next_attempt_at <= NOW()) ORDER BY priority DESC, created_at ASC LIMIT 1 "); $stmt->execute([self::MAX_ATTEMPTS]); return $stmt->fetch(PDO::FETCH_ASSOC); } /** * Wysyła email */ private function sendEmail($emailData) { $this->incrementAttempts($emailData['id']); try { // Próba wysłania emaila $success = $this->mailer->send( $emailData['recipient'], $emailData['subject'], $emailData['body'] ); if ($success) { $this->markEmailAsSent($emailData['id']); $this->updateLastSentTime(); return true; } else { $this->handleFailedEmail($emailData); return false; } } catch (Exception $e) { $this->handleFailedEmail($emailData, $e->getMessage()); return false; } } /** * Zwiększa liczbę prób wysłania */ private function incrementAttempts($emailId) { $stmt = $this->db->prepare(" UPDATE email_queue SET attempts = attempts + 1, last_attempt_at = NOW() WHERE id = ? "); $stmt->execute([$emailId]); } /** * Oznacza email jako wysłany */ private function markEmailAsSent($emailId) { $stmt = $this->db->prepare(" UPDATE email_queue SET status = 'sent', sent_at = NOW() WHERE id = ? "); $stmt->execute([$emailId]); } /** * Aktualizuje czas ostatniego wysłania */ private function updateLastSentTime() { $stmt = $this->db->prepare(" INSERT INTO email_settings (id, last_sent_at) VALUES (1, NOW()) ON DUPLICATE KEY UPDATE last_sent_at = NOW() "); $stmt->execute(); } /** * Obsługuje nieudane wysłanie emaila */ private function handleFailedEmail($emailData, $errorMessage = null) { if ($emailData['attempts'] >= self::MAX_ATTEMPTS) { // Maksymalna liczba prób osiągnięta $stmt = $this->db->prepare(" UPDATE email_queue SET status = 'failed', error_message = ? WHERE id = ? "); $stmt->execute([$errorMessage, $emailData['id']]); } else { // Zaplanuj kolejną próbę za 5 minut $stmt = $this->db->prepare(" UPDATE email_queue SET next_attempt_at = DATE_ADD(NOW(), INTERVAL 5 MINUTE), error_message = ? WHERE id = ? "); $stmt->execute([$errorMessage, $emailData['id']]); } } /** * Pobiera statystyki kolejki */ public function getQueueStats() { $stmt = $this->db->prepare(" SELECT status, COUNT(*) as count FROM email_queue GROUP BY status "); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } /** * Czyści stare emaile (opcjonalne) */ public function cleanOldEmails($daysOld = 30) { $stmt = $this->db->prepare(" DELETE FROM email_queue WHERE status IN ('sent', 'failed') AND created_at < DATE_SUB(NOW(), INTERVAL ? DAY) "); return $stmt->execute([$daysOld]); } } // Przykład użycia class EmailProcessor { private $emailQueue; public function __construct($emailQueue) { $this->emailQueue = $emailQueue; } /** * Uruchamia przetwarzanie kolejki (można wywołać przez cron) */ public function run() { echo "Rozpoczynam przetwarzanie kolejki emaili...\n"; $processed = 0; while ($this->emailQueue->processQueue()) { $processed++; echo "Wysłano email #{$processed}\n"; // Przerwa 2 minuty przed następnym emailem sleep(120); } if ($processed === 0) { echo "Brak emaili do wysłania lub zbyt wcześnie na kolejny email.\n"; } // Wyświetl statystyki $stats = $this->emailQueue->getQueueStats(); echo "Statystyki kolejki:\n"; foreach ($stats as $stat) { echo "- {$stat['status']}: {$stat['count']}\n"; } } } // Przykład inicjalizacji /* $pdo = new PDO('mysql:host=localhost;dbname=your_db', $username, $password); $mailer = new YourMailer(); // Twoja klasa mailera z metodą send() $emailQueue = new EmailQueue($pdo, $mailer); $processor = new EmailProcessor($emailQueue); // Dodanie emaila do kolejki $emailQueue->addEmail('user@example.com', 'Test Subject', 'Test Body', 1); // Przetwarzanie kolejki $processor->run(); */Potrzebne tabele w bazie danych:
-- Tabela kolejki emaili CREATE TABLE email_queue ( id INT AUTO_INCREMENT PRIMARY KEY, recipient VARCHAR(255) NOT NULL, subject VARCHAR(500) NOT NULL, body TEXT NOT NULL, priority INT DEFAULT 1, status ENUM('pending', 'sent', 'failed') DEFAULT 'pending', attempts INT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_attempt_at TIMESTAMP NULL, next_attempt_at TIMESTAMP NULL, sent_at TIMESTAMP NULL, error_message TEXT NULL, INDEX idx_status_priority (status, priority), INDEX idx_next_attempt (next_attempt_at) ); -- Tabela ustawień (dla śledzenia ostatniego wysłania) CREATE TABLE email_settings ( id INT PRIMARY KEY, last_sent_at TIMESTAMP NULL );System działa następująco:
- Dodawanie emaili: Metoda
addEmail()dodaje emaile do kolejki z priorytetem - Ograniczenie czasowe: Sprawdza czy minęły 2 minuty od ostatniego wysłania
- Przetwarzanie:
processQueue()pobiera następny email i próbuje go wysłać - Obsługa błędów: Przy niepowodzeniu planuje kolejną próbę, maksymalnie 3 próby
- Monitoring: Dostępne są statystyki i możliwość czyszczenia starych rekordów
Możesz uruchomić
EmailProcessor::run()przez cron job co kilka minut, aby automatycznie przetwarzać kolejkę.- Dodawanie emaili: Metoda
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.