swiftlys2/docs/api/releases/features/ai/

Scheduler

SwiftlyS2 provides a scheduler service for main-thread dispatching and timer-based execution, available through APIISwiftlyCore.Scheduler (APIISchedulerService). Every callback you hand to it runs on the game thread, so it is the way to call thread-unsafe APIs from a background flow or to delay work until later.

Scheduling on the Main Loop

APIISchedulerService.NextTick runs a callback on the next server tick; APIISchedulerService.NextWorldUpdate runs on the next world update phase instead:

Core.Scheduler.NextTick(() => Console.WriteLine("Runs on next tick."));
Core.Scheduler.NextWorldUpdate(() => Console.WriteLine("Runs on next world update."));

Both take an Action and return void.

Awaitable Variants

APIISchedulerService.NextTickAsync and APIISchedulerService.NextWorldUpdateAsync take the same Action/Func<T> overloads and can be awaited - the Action overloads return Task, the Func<T> overloads return Task<T>:

await Core.Scheduler.NextTickAsync(() => Console.WriteLine("Executed on next tick, awaited."));
 
int computedValue = await Core.Scheduler.NextWorldUpdateAsync(() => 42);

Don't pass an async callback (Func<Task>/Func<Task<T>>) to NextTick, NextTickAsync, NextWorldUpdate, or NextWorldUpdateAsync - those overloads are [Obsolete] and throw InvalidOperationException, since an async callback can resume on a different thread and break the main-thread guarantee these methods exist for. Use the plain Action/Func<T> overloads instead.

Timer APIs

Every timer method returns a CancellationTokenSource you can cancel, and takes the callback as an Action that runs on the game thread.

Tick-Based Timers

var delayCts = Core.Scheduler.Delay(128, () => Console.WriteLine("Executed once after 128 ticks."));
var repeatCts = Core.Scheduler.Repeat(64, () => Console.WriteLine("Runs immediately, then every 64 ticks."));
var delayRepeatCts = Core.Scheduler.DelayAndRepeat(32, 64, () => Console.WriteLine("Starts after 32 ticks, then repeats every 64 ticks."));

Intervals for these three are int ticks. See APIISchedulerService.Delay, APIISchedulerService.Repeat, and APIISchedulerService.DelayAndRepeat.

Second-Based Timers

APIISchedulerService.DelayBySeconds, APIISchedulerService.RepeatBySeconds, and APIISchedulerService.DelayAndRepeatBySeconds mirror the tick-based methods above with float seconds instead of raw ticks:

Core.Scheduler.DelayBySeconds(2.0f, () => Console.WriteLine("Executed after 2 seconds."));
Core.Scheduler.RepeatBySeconds(0.5f, () => Console.WriteLine("Runs immediately, then every 0.5 seconds."));

Second-based timers are still driven by game ticks, so timing gets inaccurate as intervals approach a single tick (~15ms).

Canceling Timers

Every timer method - Delay, Repeat, DelayAndRepeat, DelayBySeconds, RepeatBySeconds, DelayAndRepeatBySeconds and AddTimer - returns a CancellationTokenSource:

var token = Core.Scheduler.Repeat(64, () => Console.WriteLine("Tick"));
 
token.Cancel(); // manual cancel
Core.Scheduler.StopOnMapChange(token); // auto-cancel on map change

See APIISchedulerService.StopOnMapChange.

Advanced Timers with AddTimer

APIISchedulerService.AddTimer takes a Func<ITimerContext, TimerStep> and supports dynamic per-execution behavior - e.g. changing the delay between runs or stopping on a condition. The callback runs again only if the returned APITimerStep says so:

var cts = Core.Scheduler.AddTimer(ctx =>
{
    Console.WriteLine($"Run #{ctx.ExecutionCount}");
    return ctx.ExecutionCount >= 4 ? TimerStep.Stop() : TimerStep.WaitForSeconds(1.0f);
});

Every run receives an APIITimerContext, whose only member is APIITimerContext.ExecutionCount - a ulong counting the runs of that timer, starting at 0 for the first one.

MemberSignatureDescription
APIITimerContext.ExecutionCountulong ExecutionCount { get; }Number of runs so far, starting at 0 for the first run

APITimerStep is an abstract record with a private constructor, so you always get one of the steps below from its static helpers:

MethodSignatureBehavior
TimerStep.Spin()static TimerStep Spin()Run again on the very next tick
TimerStep.WaitForTicks(long ticks)static TimerStep WaitForTicks(long ticks)Wait the given number of ticks before the next run
TimerStep.WaitForMilliseconds(long milliseconds)static TimerStep WaitForMilliseconds(long milliseconds)Wait the given number of milliseconds before the next run
TimerStep.WaitForSeconds(float seconds)static TimerStep WaitForSeconds(float seconds)Wait the given number of seconds before the next run (converted to milliseconds internally)
TimerStep.Stop()static TimerStep Stop()Stop the timer, no further runs

WaitForTicks and WaitForMilliseconds require an argument greater than 0 and throw ArgumentException otherwise. Since WaitForSeconds is converted to whole milliseconds, sub-millisecond values round down to 0 and are rejected the same way.

Members

APIISchedulerService members, in the SwiftlyS2.Shared.Scheduler namespace:

MemberSignatureReturns
APIISchedulerService.NextTickvoid NextTick(Action task)-
APIISchedulerService.NextTickAsyncTask NextTickAsync(Action task)Completes once task has run on the next tick
APIISchedulerService.NextTickAsyncTask<T> NextTickAsync<T>(Func<T> task)The value returned by task
APIISchedulerService.NextWorldUpdatevoid NextWorldUpdate(Action task)-
APIISchedulerService.NextWorldUpdateAsyncTask NextWorldUpdateAsync(Action task)Completes once task has run on the next world update
APIISchedulerService.NextWorldUpdateAsyncTask<T> NextWorldUpdateAsync<T>(Func<T> task)The value returned by task
APIISchedulerService.DelayCancellationTokenSource Delay(int delayTick, Action task)Cancellation source for the timer
APIISchedulerService.RepeatCancellationTokenSource Repeat(int periodTick, Action task)Cancellation source for the timer
APIISchedulerService.DelayAndRepeatCancellationTokenSource DelayAndRepeat(int delayTick, int periodTick, Action task)Cancellation source for the timer
APIISchedulerService.DelayBySecondsCancellationTokenSource DelayBySeconds(float delaySeconds, Action task)Cancellation source for the timer
APIISchedulerService.RepeatBySecondsCancellationTokenSource RepeatBySeconds(float periodSeconds, Action task)Cancellation source for the timer
APIISchedulerService.DelayAndRepeatBySecondsCancellationTokenSource DelayAndRepeatBySeconds(float delaySeconds, float periodSeconds, Action task)Cancellation source for the timer
APIISchedulerService.AddTimerCancellationTokenSource AddTimer(Func<ITimerContext, TimerStep> task)Cancellation source for the timer
APIISchedulerService.StopOnMapChangevoid StopOnMapChange(CancellationTokenSource cts)-

On top of those, NextTick, NextTickAsync, NextWorldUpdate and NextWorldUpdateAsync each declare two [Obsolete] overloads taking Func<Task?>/Func<Task<T?>>; they throw InvalidOperationException and are documented in the callout above only so you don't use them.

Reference

See Thread Safety for when to dispatch through Core.Scheduler instead of calling a thread-unsafe API directly, and Swiftly Core for the full service list.