Play Strawberry Docs
Scripts

Scheduler

Sync tasks run on the game tick, async tasks run beside it; both count game ticks and can be cancelled.

Sync and async tasks

The scheduler follows Paper's model. scheduler::SchedulerExt is implemented for Context and Server:

  • Sync tasks: schedule_delayed_task(delay_ticks, handler) and schedule_repeating_task(delay_ticks, period_ticks, handler) (Paper's runTaskLater and runTaskTimer). They run at the start of a game tick, before the tick's world work, and the tick waits for them.
  • Async tasks: schedule_delayed_async_task and schedule_repeating_async_task (Paper's ...Asynchronously). They start at that point but run beside the tick; the tick never waits for them.

Each function returns a task id. The handler is a closure Fn(Server) + Send + Sync + 'static. Delays and periods count game ticks: 20 ticks are one second at the normal rate, longer when the server runs behind. A period of 0 counts as 1.

rust
fn start_tasks(context: &Context) {
    // A sync task: runs at the start of a tick, and the tick waits for it.
    // 20 ticks = 1 second at the normal tick rate.
    let id = context.schedule_repeating_task(20, 20, |server: Server| {
        let left = SECONDS_LEFT.fetch_sub(1, Ordering::Relaxed);
        for player in server.get_all_players() {
            player.show_actionbar(TextComponent::text(&format!("Event starts in {left} s")));
        }
        if left <= 1 {
            // Stops the repeating task: a run that has not started yet does not start.
            if let Some(id) = COUNTDOWN_TASK.lock().ok().and_then(|mut task| task.take()) {
                cancel_task(id);
            }
        }
    });
    if let Ok(mut task) = COUNTDOWN_TASK.lock() {
        *task = Some(id);
    }

    // An async task: starts after 5 seconds and runs off the game tick.
    // Good for work the tick should not wait for, such as writing a file.
    context.schedule_delayed_async_task(100, |_server: Server| {
        log(LogLevel::Info, "Five seconds after load.");
    });
}

One call at a time

Your script runs one call at a time. While one of your async tasks runs, your event handlers, commands and sync tasks wait for it, and so does every event that waits for one of your blocking handlers. Keep async work short or split it into steps. A repeating async run that falls due while the previous run has not ended is skipped.

Cancel

scheduler::cancel_task(task_id) removes one of your tasks: a run that has not started does not start; a run that has started finishes. The closure of a one-shot task is released after its run, a repeating task's when it is cancelled. Unloading your script removes all its tasks.

Keep tasks small

  • Look players and entities up again in each run instead of keeping handles for a long time.
  • Never block a sync task on a file or a long loop: the whole server waits for it.
  • Count the work you do per run and stop when the job is done or the player has left.

On this page