TimerX and scheduled work
On this page
Periodic work
TimerX shares schedulers and supports synchronous, Task and ValueTask callbacks. Integer dueTime, period and SetNext values use milliseconds. This callback runs once per second; the example cancels after about three seconds:
using TUtility;
using var cancellation = new CancellationTokenSource();
using var timer = new TimerX(TickAsync, cancellation.Token, 0, 1000)
{
Reentrant = false
};
await Task.Delay(3100);
cancellation.Cancel();
/// <summary>按宿主取消状态执行一次轻量周期工作。</summary>
static Task TickAsync(object? state)
{
var token = (CancellationToken)state!;
token.ThrowIfCancellationRequested();
Console.WriteLine(DateTime.UtcNow.ToString("O"));
return Task.CompletedTask;
}Use async overloads to retain observable completion. Long synchronous callbacks occupy the scheduler thread; Async controls thread-pool dispatch for those callbacks. Reentrant = false prevents overlapping invocations of this timer, without establishing cross-process exclusion.
Control and observation
| Member | Purpose |
|---|---|
Period / Change | Period and due-time parameters |
SetNext(ms) | Adjust the next trigger |
Calling / Cost | Execution state and callback cost |
NextTime / Disposed | Next trigger time and disposal state |
TimerScheduler | Scheduler management and named isolation |
Dispose() cancels future scheduling; it does not promise to await all active callbacks. Hosts cancel business work, track and await owned operations, then release databases, files and network resources.
Cron expressions
Cron uses six fields: second minute hour day month weekday.
| Expression | Meaning |
|---|---|
*/10 * * * * * | Every ten seconds |
0 */5 * * * * | Every five minutes at second zero |
0 0 2 * * 1-5 | Weekdays at 02:00 |
0 0 0 1 * * | Midnight on the first day of each month |
Cron.Parse reports parsing success, IsTime(DateTime) checks a match and GetNext(DateTime) finds the next time. Sunday defaults to zero and is adjustable with Sunday; timezone and daylight-saving behavior depend on the scheduler and input time.
Host-aware task wrappers
ScheduledSyncTask, ScheduledAsyncTask and CronScheduledTask implement IScheduledTask, exposing Start, Stop, SetNext and Change. Cron wrappers accept callbacks with a CancellationToken and an onError callback.
Schedulers do not persist execution history or replay missed jobs. The application implements multi-instance exclusion and failure compensation.