Skip to main content

Scheduler

Struct Scheduler 

Source
pub struct Scheduler { /* private fields */ }
Expand description

IO-aware priority scheduler.

Coordinates task execution by:

  1. Popping highest-priority pending tasks from the SQLite store
  2. Checking IO budget against running task estimates and system capacity
  3. Applying backpressure throttling based on external pressure sources
  4. Preempting lower-priority tasks when high-priority work arrives
  5. Managing retries and failure recording
  6. Emitting lifecycle events for UI integration

Scheduler is Clone — each clone shares the same underlying state. This makes it easy to hold in tauri::State<Scheduler> or share across async tasks.

Implementations§

Source§

impl Scheduler

Source

pub fn new( store: TaskStore, config: SchedulerConfig, registry: Arc<TaskTypeRegistry>, pressure: CompositePressure, policy: ThrottlePolicy, ) -> Self

Source

pub fn builder() -> SchedulerBuilder

Create a SchedulerBuilder for ergonomic construction.

Source

pub fn subscribe(&self) -> Receiver<SchedulerEvent>

Subscribe to scheduler lifecycle events.

Returns a broadcast receiver. Events are emitted on task dispatch, completion, failure, preemption, cancellation, and progress. Useful for bridging to a Tauri frontend or updating UI state.

Source

pub async fn set_resource_reader(&self, reader: Arc<dyn ResourceReader>)

Set the resource reader for IO-aware scheduling.

Source

pub fn store(&self) -> &TaskStore

Get a reference to the underlying store for direct queries.

Source

pub async fn register_state<T: Send + Sync + 'static>(&self, state: Arc<T>)

Register shared application state after the scheduler has been built.

This is useful when library code (e.g. shoebox) needs to inject its own state into a scheduler that was constructed by a parent application. Multiple types can coexist — each is keyed by TypeId.

Source

pub async fn submit( &self, sub: &TaskSubmission, ) -> Result<SubmitOutcome, StoreError>

Submit a task.

If the task’s priority meets the preemption threshold, running tasks with lower priority are preempted (their cancellation tokens are cancelled and they are paused in the store).

Source

pub async fn submit_batch( &self, submissions: &[TaskSubmission], ) -> Result<Vec<SubmitOutcome>, StoreError>

Submit multiple tasks in a single SQLite transaction.

Preemption is triggered once at the end if any inserted or upgraded task has high enough priority.

Source

pub async fn submit_typed<T: TypedTask>( &self, task: &T, ) -> Result<SubmitOutcome, StoreError>

Submit a TypedTask, handling serialization automatically.

Uses the priority from TypedTask::priority().

Source

pub async fn submit_typed_at<T: TypedTask>( &self, task: &T, priority: Priority, ) -> Result<SubmitOutcome, StoreError>

Submit a TypedTask with an explicit priority override.

The provided priority replaces whatever TypedTask::priority() would return, keeping priority out of the serialized payload.

Source

pub async fn task_lookup( &self, task_type: &str, dedup_input: Option<&[u8]>, ) -> Result<TaskLookup, StoreError>

Look up a task by the same inputs used during submission.

Computes the dedup key from task_type and dedup_input (the explicit key string or payload bytes — whichever was used when submitting), then checks the active queue and history in one call.

§Examples
// Using an explicit key (same as TaskSubmission.key = Some("my-file.jpg"))
let result = scheduler.task_lookup("thumbnail", Some(b"my-file.jpg")).await?;

// Using payload-based dedup (same as TaskSubmission.key = None, payload = ...)
let result = scheduler.task_lookup("ingest", Some(&payload_bytes)).await?;
Source

pub async fn lookup_typed<T: TypedTask>( &self, task: &T, ) -> Result<TaskLookup, StoreError>

Look up a TypedTask by value, using its serialized form as the dedup input.

This mirrors submit_typed — pass the same struct you would submit and get back its current status.

Source

pub async fn cancel(&self, task_id: i64) -> Result<bool, StoreError>

Cancel a task by id.

If the task is currently running, its cancellation token is triggered and it is removed from the active map. If it is pending or paused, it is deleted from the store. Returns true if the task was found and cancelled.

Source

pub async fn try_dispatch(&self) -> Result<bool, StoreError>

Try to pop and execute the next task.

Returns true if a task was dispatched, false if no work was available (empty queue, concurrency limit, IO budget exhausted, or throttled).

Source

pub async fn run(&self, token: CancellationToken)

Run the scheduler loop until the cancellation token is triggered.

This is the main entry point. The loop wakes on three conditions:

  1. Cancellation — triggers shutdown.
  2. Notification — a task was submitted or the scheduler was resumed.
  3. Poll interval — periodic housekeeping (e.g. resuming paused tasks).

On mobile targets (iOS/Android), the notify-based wake avoids the constant 500ms polling that would otherwise prevent the CPU from sleeping.

Source

pub async fn active_tasks(&self) -> Vec<TaskRecord>

Snapshot of currently active (in-memory) tasks.

Source

pub async fn estimated_progress(&self) -> Vec<EstimatedProgress>

Get estimated progress for all running tasks.

Combines executor-reported progress with throughput-based extrapolation using historical average duration for each task type.

Source

pub async fn snapshot(&self) -> Result<SchedulerSnapshot, StoreError>

Capture a single status snapshot for dashboard UIs.

Gathers running tasks, queue depths, progress estimates, and backpressure in one call — exactly what a Tauri command would return to the frontend.

Source

pub fn set_max_concurrency(&self, limit: usize)

Update max concurrency at runtime (e.g., from adaptive controller or in response to battery/thermal state).

Source

pub fn max_concurrency(&self) -> usize

Read current max concurrency setting.

Source

pub async fn pause_all(&self)

Pause the entire scheduler.

Stops the run loop from dispatching new tasks and pauses all currently running tasks (their cancellation tokens are triggered and they are moved back to the paused state in the store so they will be re-dispatched on resume).

Useful when the app is backgrounded, the laptop goes to sleep, or the user clicks “pause all” in the UI.

Source

pub async fn resume_all(&self)

Resume the scheduler after a pause_all.

Clears the pause flag so the run loop will resume dispatching on its next poll tick. Tasks that were paused in the store will be picked up automatically.

Source

pub fn is_paused(&self) -> bool

Returns true if the scheduler is globally paused.

Trait Implementations§

Source§

impl Clone for Scheduler

Source§

fn clone(&self) -> Scheduler

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more