Skip to main content

WorkerUtils

Struct WorkerUtils 

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

The WorkerUtils struct provides a set of utility methods for managing jobs.

This is the primary interface for adding jobs to the queue, managing existing jobs, performing maintenance tasks, and migrating the database schema.

Implementations§

Source§

impl WorkerUtils

Source

pub fn new(database: impl Into<Database>, schema: impl Into<Schema>) -> Self

Creates a new instance of WorkerUtils.

§Arguments
  • database - Database connection handle
  • schema - The schema where Graphile Worker tables are stored
§Returns

A new WorkerUtils instance

Source

pub fn with_hooks(self, hooks: Arc<HookRegistry>) -> Self

Adds lifecycle hooks to this WorkerUtils instance.

Source

pub fn with_task_details(self, task_details: SharedTaskDetails) -> Self

Adds task details to this WorkerUtils instance.

When task_details is provided, cleanup operations that include GcTaskIdentifiers will automatically refresh the task details to ensure the worker can still pick up jobs after task identifiers are garbage collected.

Source

pub fn with_use_local_time(self, use_local_time: bool) -> Self

Sets whether to use local application time or database time for timestamps.

When use_local_time is true, the application’s Utc::now() is used for timestamps, which can help handle clock drift between the application server and database server. When false (default), PostgreSQL’s now() is used instead.

Source§

impl WorkerUtils

Source

pub async fn remove_job(&self, job_key: &str) -> Result<(), GraphileWorkerError>

Removes a job from the queue by its job key.

Useful for cancelling scheduled jobs that haven’t run yet.

Source

pub async fn complete_jobs( &self, ids: &[i64], ) -> Result<Vec<DbJob>, GraphileWorkerError>

Marks multiple jobs as completed.

Source

pub async fn permanently_fail_jobs( &self, ids: &[i64], reason: &str, ) -> Result<Vec<DbJob>, GraphileWorkerError>

Marks multiple jobs as permanently failed with a reason.

Source

pub async fn reschedule_jobs( &self, ids: &[i64], options: RescheduleJobOptions, ) -> Result<Vec<DbJob>, GraphileWorkerError>

Reschedules multiple jobs with new parameters.

This allows changing when jobs will run next, their priority, and their retry behavior.

Source

pub async fn list_active_workers( &self, sweep_threshold: Duration, ) -> Result<Vec<ActiveWorkerRow>, GraphileWorkerError>

Lists workers registered in the heartbeat table.

Source

pub async fn sweep_stale_workers( &self, options: SweepStaleWorkersOptions, ) -> Result<SweepStaleWorkersResult, GraphileWorkerError>

Sweeps inactive workers and orphan locks, recovering their jobs.

Source

pub async fn sweep_stale_workers_with_config( &self, recovery_config: &WorkerRecoveryConfig, options: SweepStaleWorkersOptions, ) -> Result<SweepStaleWorkersResult, GraphileWorkerError>

Sweeps inactive workers with an explicit recovery configuration.

Source

pub async fn force_unlock_workers( &self, worker_ids: &[&str], ) -> Result<(), GraphileWorkerError>

Force unlocks worker records in the database.

Useful for recovering from situations where workers crashed without properly releasing their locks, allowing their jobs to be picked up by other workers.

Source

pub async fn cleanup( &self, tasks: &[CleanupTask], ) -> Result<(), GraphileWorkerError>

Runs database cleanup tasks to maintain performance.

When GcTaskIdentifiers is included in the tasks and this WorkerUtils instance was created with task details (via with_task_details), the task identifiers known to this worker will be preserved and refreshed after cleanup.

Source

pub async fn migrate(&self) -> Result<(), MigrateError>

Runs database migrations to ensure the schema is up to date.

Source§

impl WorkerUtils

Source

pub async fn add_job<T: TaskHandler>( &self, payload: T, spec: JobSpec, ) -> Result<Job, GraphileWorkerError>

Adds a job to the queue with type safety.

Uses the TaskHandler trait to ensure that the job identifier and payload type match, providing compile-time type safety.

§Example
let job = utils.add_job(
    MyTask { data: "hello".to_string() },
    JobSpec::default()
).await?;
Source

pub async fn add_raw_job<P>( &self, identifier: &str, payload: P, spec: JobSpec, ) -> Result<Job, GraphileWorkerError>
where P: Serialize,

Adds a job to the queue with a raw identifier and payload.

Doesn’t require the task handler to be defined at compile time, allowing for dynamic job creation. However, lacks the compile-time type safety of add_job.

§Example
let job = utils.add_raw_job(
    "send_email",
    json!({ "to": "user@example.com", "subject": "Hello" }),
    JobSpec::default()
).await?;
Source

pub async fn add_jobs<T: TaskHandler + Clone>( &self, jobs: &[(T, &JobSpec)], ) -> Result<Vec<Job>, GraphileWorkerError>

Adds multiple jobs of the same type to the queue in a single batch operation.

This is more efficient than calling add_job multiple times when you need to add many jobs of the same type, as it uses a single database round trip.

§Limitations
  • job_key_mode: UnsafeDedupe is not supported in batch operations
  • job_key_mode is applied uniformly: if any job uses PreserveRunAt, it applies to all jobs in the batch. For per-job job_key_mode control, use add_job individually.
Source

pub async fn add_raw_jobs( &self, jobs: &[RawJobSpec], ) -> Result<Vec<Job>, GraphileWorkerError>

Adds multiple jobs with raw identifiers and payloads in a single batch operation.

This allows adding jobs of different types in a single batch, but without compile-time type safety. More efficient than multiple add_raw_job calls.

§Limitations
  • job_key_mode: UnsafeDedupe is not supported in batch operations
  • job_key_mode is applied uniformly: if any job uses PreserveRunAt, it applies to all jobs in the batch. For per-job job_key_mode control, use add_raw_job individually.
Source

pub async fn add_batch_job<T: BatchTaskHandler>( &self, payloads: Vec<T>, spec: JobSpec, ) -> Result<Job, GraphileWorkerError>

Adds a batch job to the queue with type safety.

The database payload is a JSON array of T items. Register the same identifier with the worker builder’s batch-job registration API so the worker can run the batch and retry only failed items after partial success.

Trait Implementations§

Source§

impl Clone for WorkerUtils

Source§

fn clone(&self) -> WorkerUtils

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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> 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