Scheduling with CRON

Run jobs using 6-field CRON expressions with seconds precision.

Full source

File: pwsh/tutorial/examples/12.2-Scheduling-Cron.ps1

<#
    Scheduling Cron Example
    Demonstrates CRON-based jobs (seconds precision) with PowerShell and C#.
    FileName: 12.2-Scheduling-Cron.ps1
#>
param(
    [int]$Port = 5000,
    [IPAddress]$IPAddress = [IPAddress]::Loopback
)

## 1. Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault

## 2. Server
New-KrServer -Name 'Scheduling Cron Demo'

## 3. Listener
Add-KrEndpoint -Port $Port -IPAddress $IPAddress

## 4. Runtime + Scheduler
Add-KrScheduling -MaxRunspaces 2

## 5. Apply configuration
Enable-KrConfiguration

## 6. CRON jobs

# (A) PowerShell job every 10 seconds, run once immediately
Register-KrSchedule -Name 'cron-ps' -Cron '*/10 * * * * *' -RunImmediately -ScriptBlock {
    Write-KrLog -Level Information -Message '⏰ cron-ps fired at {0:O}' -Values $([DateTimeOffset]::UtcNow)
}

# (B) C# job every 15 seconds, run once immediately
Register-KrSchedule -Name 'cron-cs' -Cron '*/15 * * * * *' -Language CSharp -RunImmediately -Code 'Serilog.Log.Information("⏰ cron-cs fired at {0:O}", DateTimeOffset.UtcNow);'

## 7. Routes
Add-KrMapRoute -Verbs Get -Pattern '/schedule/report' -ScriptBlock {
    $report = Get-KrScheduleReport
    Write-KrJsonResponse -InputObject $report -StatusCode 200
}

## 8. Start
Start-KrServer -CloseLogsOnExit


Notes:

  • Use */N in the first field (seconds) for sub-minute cadence.
  • Combine PowerShell ScriptBlock and inline C# code as needed.
  • CRON format: six-field (seconds minutes hours day month day-of-week)

Step-by-step

  1. Enable the scheduler subsystem.
  2. Register a job with a 6-field CRON expression (seconds precision).
  3. Mix PowerShell ScriptBlock or inline C# as needed for job bodies.
  4. Observe execution over time; adjust timing with CRON fields.

Try it

pwsh .\docs\_includes\examples\pwsh\12.2-Scheduling-Cron.ps1
# Observe logs for scheduled job runs over the next ~30 seconds

Troubleshooting

Symptom Cause Fix
Job not firing CRON expression invalid Validate 6-field CRON and test with a short cadence like */5 * * * * *
Too frequent or too slow Misplaced */N field Ensure seconds field is first and uses */N for sub-minute
Overlapping runs Long-running job Consider concurrency control or longer intervals

References


Previous / Next

Previous: Scheduling Quickstart Next: Scheduling Report endpoint