using DownloadManager.Core.Models; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace DownloadManager.Core.Services; public class SchedulerWatchdog { private readonly IScheduleService _scheduleService; private readonly IDownloadService _downloadService; private Timer? _timer; private bool _isProcessing; public SchedulerWatchdog(IScheduleService scheduleService, IDownloadService downloadService) { _scheduleService = scheduleService; _downloadService = downloadService; } public void Start() { // Her 30 saniyede bir kontrol et _timer = new Timer(async _ => await CheckScheduleAsync(), null, TimeSpan.Zero, TimeSpan.FromSeconds(30)); Serilog.Log.Information("Zamanlayıcı İzleyici (Watchdog) başlatıldı."); } public void Stop() { _timer?.Dispose(); Serilog.Log.Information("Zamanlayıcı İzleyici durduruldu."); } private async Task CheckScheduleAsync() { if (_isProcessing) return; _isProcessing = true; try { var jobs = await _scheduleService.GetJobsAsync(); var activeJob = jobs.FirstOrDefault(j => j.IsActive); if (activeJob == null) return; var now = DateTime.Now; var currentTime = now.TimeOfDay; // Gün kontrolü int dayIndex = (int)now.DayOfWeek; // 0=Pazar, 1=Pazartesi... // Model Pt=0, Pz=6 şeklinde varsayılmıştı (1111111) // .NET DayOfWeek: Sunday=0, Monday=1... // Dönüştürelim: Pt=0 için int adjustedIndex = dayIndex == 0 ? 6 : dayIndex - 1; if (activeJob.DaysOfWeek[adjustedIndex] == '0') return; // Başlatma kontrolü if (activeJob.StartTime.HasValue) { var startTime = activeJob.StartTime.Value.TimeOfDay; // Başlangıç vaktinden sonraki 1 dakika içindeysek başlat (sürekli tetiklenmemesi için) if (currentTime >= startTime && currentTime < startTime.Add(TimeSpan.FromMinutes(1))) { await StartScheduledDownloads(); } } // Durdurma kontrolü if (activeJob.EndTime.HasValue) { var endTime = activeJob.EndTime.Value.TimeOfDay; if (currentTime >= endTime && currentTime < endTime.Add(TimeSpan.FromMinutes(1))) { await StopAllDownloads(); } } } catch (Exception ex) { Serilog.Log.Error(ex, "Zamanlayıcı kontrolü sırasında hata oluştu."); } finally { _isProcessing = false; } } private async Task StartScheduledDownloads() { Serilog.Log.Information("Zamanlayıcı: İndirmeler başlatılıyor..."); var downloads = await _downloadService.GetAllDownloadsAsync(); var pending = downloads.Where(d => d.Status == Enums.DownloadStatus.Paused || d.Status == Enums.DownloadStatus.Pending); foreach (var item in pending) { await _downloadService.ResumeDownloadAsync(item.Id); } } private async Task StopAllDownloads() { Serilog.Log.Information("Zamanlayıcı: İndirmeler durduruluyor..."); var downloads = await _downloadService.GetAllDownloadsAsync(); var active = downloads.Where(d => d.Status == Enums.DownloadStatus.Downloading || d.Status == Enums.DownloadStatus.Queued); foreach (var item in active) { await _downloadService.PauseDownloadAsync(item.Id); } } }