Skip to main content

PersistentJobQueue

Struct PersistentJobQueue 

Source
pub struct PersistentJobQueue { /* private fields */ }
Available on crate feature jobs and (crate features model-mysql or model-postgres or model-sqlite) only.
Expand description

A job queue backed by the model layer (model-sqlite / model-postgres / model-mysql): jobs are written to a rws_jobs table before being acknowledged, so pending and retrying jobs survive a process crash or restart, and several replicas can share one queue.

Unlike JobQueue, a job here can’t be an arbitrary closure — a closure can’t be serialized to disk. Instead the queue stores (job_type, payload) as plain text and dispatches to a handler registered for that job_type at execution time. Register every handler you enqueue before calling start, including after a restart — unprocessed rows from a previous run (and any row left running when the process crashed) are picked up automatically.

Since 18.35.0 (#93) a job can wait until a time, go to a named queue with a priority, be unique (EnqueueOptions); a job that exhausts its retries stays in the table as failed — the dead-letter list (failed_jobs, retry, on_dead); and schedule runs a job on a cron schedule once per due time across every replica.

CREATE TABLE IF NOT EXISTS rws_jobs (
    id          VARCHAR(64) PRIMARY KEY,
    job_type    TEXT    NOT NULL,
    payload     TEXT    NOT NULL DEFAULT '',
    status      TEXT    NOT NULL DEFAULT 'pending', -- pending | running | failed
    attempts    INTEGER NOT NULL DEFAULT 0,
    max_retries INTEGER NOT NULL DEFAULT 3,
    next_run_at BIGINT  NOT NULL,
    created_at  BIGINT  NOT NULL,
    last_error  TEXT,
    queue       VARCHAR(64) NOT NULL DEFAULT 'default',
    priority    BIGINT  NOT NULL DEFAULT 0,
    unique_key  VARCHAR(191)
)

A table from before 18.35.0 gets the last three columns added. Completed jobs are deleted.

Implementations§

Source§

impl PersistentJobQueue

Source

pub async fn new(pool: DbPool) -> Result<Self, DbError>

Creates the queue and its backing rws_jobs table if absent (adding the 18.35.0 columns to an older one), then resets any row left running (interrupted by a previous crash) back to pending so it gets picked up again.

Source

pub fn max_retries(self, n: u32) -> Self

Override the default retry count applied to jobs enqueued via enqueue (default: 3). Use EnqueueOptions::max_retries for a per-job override.

Source

pub fn poll_interval(self, interval: Duration) -> Self

Override how often idle workers poll for due jobs (default: 500 ms).

Source

pub fn backoff(self, initial: Duration, multiplier: u32) -> Self

Override the backoff policy applied between retries: initial delay before the first retry, doubled (or scaled by multiplier) on each subsequent attempt. Default: 500 ms initial, 2x multiplier.

Source

pub fn queues(self, names: &[&str]) -> Self

Only run jobs from these named queues (default: every queue) — one process for mailers, another for the rest.

Source

pub fn schedule( self, name: &str, cron: &str, job_type: &str, payload: &str, ) -> Result<Self, String>

Enqueue job_type with payload on the cron schedule cron (six fields, seconds first, UTC; see Scheduler). Every replica can declare the same schedule: each due time is claimed by exactly one of them (a compare-and-set on the rws_job_schedules row named name), which enqueues the job.

Source

pub fn schedule_with( self, name: &str, cron: &str, job_type: &str, payload: &str, options: EnqueueOptions, ) -> Result<Self, String>

schedule with options for the enqueued jobs.

Source

pub fn on_dead(&self, hook: impl Fn(&JobInfo) + Send + Sync + 'static)

Call hook with each job that exhausts its retries, as it moves to the dead-letter list (status = 'failed').

Source

pub fn register( &self, job_type: &str, handler: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static, )

Register the function that executes jobs of job_type. Call before start — jobs enqueued for an unregistered job_type fail immediately (and retry, same as any other handler error).

Source

pub async fn enqueue( &self, job_type: &str, payload: &str, ) -> Result<String, DbError>

Persist a new job using the queue’s defaults. Returns the job id.

Source

pub async fn enqueue_with_retries( &self, job_type: &str, payload: &str, max_retries: u32, ) -> Result<String, DbError>

Persist a new job with a per-job retry override.

Source

pub async fn enqueue_with( &self, job_type: &str, payload: &str, options: EnqueueOptions, ) -> Result<String, DbError>

Persist a new job with options (18.35.0). Returns its id — for a unique job already pending or running, that job’s id, and nothing is inserted.

Source

pub async fn tick(&self) -> Result<bool, DbError>

Run one poll-claim-execute cycle. Returns Ok(true) if a job was claimed (whether it succeeded, failed, or is retrying), Ok(false) if none was due. Exposed for tests and for embedding in a caller-owned loop; most applications should use start instead.

Source

pub async fn tick_schedules(&self) -> Result<usize, DbError>

Enqueue the scheduled jobs that are due, each due time once across every process sharing the database. Returns how many this call enqueued. start’s first worker calls it about once a second; exposed for tests and caller-owned loops.

Source

pub async fn jobs( &self, status: Option<&str>, limit: usize, ) -> Result<Vec<JobInfo>, DbError>

Jobs with status (pending, running, failed; None: all), highest priority and earliest due first, at most limit.

Source

pub async fn failed_jobs(&self, limit: usize) -> Result<Vec<JobInfo>, DbError>

The dead-letter list: jobs that exhausted their retries.

Source

pub async fn retry(&self, id: &str) -> Result<bool, DbError>

Put a failed job back in the queue, due now, with its attempts reset. false when there’s no failed job id.

Source

pub async fn delete(&self, id: &str) -> Result<bool, DbError>

Delete a job that isn’t running. false when there’s no such job.

Source

pub fn start(self: Arc<Self>, workers: usize) -> Vec<JoinHandle<()>>

Spawn workers background OS threads, each running its own single-threaded Tokio runtime, polling for due jobs at poll_interval (default: 500 ms) whenever the queue is empty; the first also enqueues scheduled jobs. Returns the thread handles; call stop then join them for a graceful shutdown.

Source

pub fn stop(&self)

Signal all worker threads spawned by start to stop after their current tick. Does not itself join the returned thread handles — join them separately to wait for a clean shutdown.

Source

pub fn pool(&self) -> &DbPool

The database the queue uses.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ServiceExt for T

Source§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Available on crate feature map-response-body only.
Apply a transformation to the response body. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using gRPC headers. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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