using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; using System; using System.Threading; using System.Threading.Tasks; using Parking_space_WebAPI.Services; public class ParkingUpdateService : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; public ParkingUpdateService(IServiceScopeFactory scopeFactory) { _scopeFactory = scopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService(); try { var yuntech_parking = await _context.yuntech_parking.FirstOrDefaultAsync(); if (yuntech_parking != null) { if (Int32.TryParse(yuntech_parking.all_num, out int totalParkingSpaces)) { var monthly_rent_data = await _context.yuntech_monthly_rent_number .FirstOrDefaultAsync(rent => rent.category == "月租"); int monthlyRentNumber = 0; if (monthly_rent_data != null) { Int32.TryParse(monthly_rent_data.number, out monthlyRentNumber); } var temporary_rent_data = await _context.yuntech_monthly_rent_number .FirstOrDefaultAsync(rent => rent.category == "臨停"); int temporaryRentNumber = 0; if (temporary_rent_data != null) { Int32.TryParse(temporary_rent_data.number, out temporaryRentNumber); } int totalOccupiedSpaces = monthlyRentNumber + Math.Abs(temporaryRentNumber); // 確保臨停車位數為絕對值 int remainingSpaces = totalParkingSpaces - totalOccupiedSpaces; // 確保剩餘車位數不為負數 yuntech_parking.now_num = Math.Max(remainingSpaces, 0).ToString(); // 保存更改 await _context.SaveChangesAsync(); } } } catch (Exception ex) { // 錯誤處理,這裡可以記錄錯誤或進行其他處理 Console.WriteLine($"An error occurred: {ex.Message}"); } } // 每 60 秒執行一次 await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } }