#Requires -Version 5.1 <# .SYNOPSIS Service loop wrapper -- runs Process-MailRules.ps1 at a configurable interval. .DESCRIPTION Designed to be launched by NSSM as a Windows service. Runs Process-MailRules.ps1 in an infinite loop, sleeping ServiceIntervalMinutes between runs. Handles graceful shutdown via Ctrl+C / console close events. .PARAMETER ConfigPath Path to config directory (default: ..\config relative to script) .EXAMPLE .\Run-ServiceLoop.ps1 .\Run-ServiceLoop.ps1 -ConfigPath "C:\work\mail-organizer\config" #> param( [string]$ConfigPath = (Join-Path $PSScriptRoot "..\config") ) # --- Load Logger --- Import-Module (Join-Path $PSScriptRoot "Logger.psm1") -Force $logDir = Join-Path (Split-Path $ConfigPath -Parent) "logs" Initialize-Logger -LogDirectory $logDir -Level "Info" # --- Read interval from settings --- $settingsFile = Join-Path $ConfigPath "settings.json" if (-not (Test-Path $settingsFile)) { Write-Log "Settings not found: $settingsFile" -Level Error exit 1 } $settings = Get-Content $settingsFile -Raw | ConvertFrom-Json $intervalMinutes = if ($settings.ServiceIntervalMinutes) { $settings.ServiceIntervalMinutes } else { 5 } # --- Graceful shutdown flag --- $script:Running = $true $cancelHandler = { $script:Running = $false Write-Log "Shutdown signal received, stopping after current run..." -Level Warn } # Register Ctrl+C / console close handler try { [Console]::TreatControlCAsInput = $false $null = Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action $cancelHandler -ErrorAction SilentlyContinue } catch { # Ignore if not supported in this host } trap { $script:Running = $false Write-Log "Service loop terminated by signal" -Level Warn break } # --- Main loop --- $processScript = Join-Path $PSScriptRoot "Process-MailRules.ps1" if (-not (Test-Path $processScript)) { Write-Log "Process-MailRules.ps1 not found: $processScript" -Level Error exit 1 } Write-Log "Service loop started (interval: $intervalMinutes min)" while ($script:Running) { Write-Log "Running Process-MailRules.ps1..." try { & $processScript -ConfigPath $ConfigPath Write-Log "Process-MailRules.ps1 completed successfully" } catch { Write-Log "Process-MailRules.ps1 failed: $_" -Level Error } if (-not $script:Running) { break } Write-Log "Waiting $intervalMinutes minute(s) until next run..." # Sleep in 1-second intervals for responsive shutdown $sleepSeconds = $intervalMinutes * 60 for ($i = 0; $i -lt $sleepSeconds; $i++) { if (-not $script:Running) { break } Start-Sleep -Seconds 1 } } Write-Log "Service loop stopped"