pub trait TaskHandler:
Serialize
+ for<'de> Deserialize<'de>
+ Send
+ Sync
+ 'static {
const IDENTIFIER: &'static str;
// Required method
fn run(
self,
ctx: WorkerContext,
) -> impl Future<Output = impl IntoTaskHandlerResult> + Send + 'static;
}Expand description
Core trait for defining task handlers in Graphile Worker.
A TaskHandler represents a specific job type that can be processed by Graphile Worker. It defines:
- A unique identifier for the task type
- The payload structure (via the implementing type’s fields)
- The execution logic in the
runmethod
§Type Requirements
Serialize: The task must be serializable to JSON for storage in the databaseDeserialize: The task must be deserializable from JSON when retrieved from the databaseSend + Sync + 'static: The task must be safe to send between threads
§Example
use graphile_worker_task_handler::{TaskHandler, IntoTaskHandlerResult};
use graphile_worker_ctx::WorkerContext;
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
struct SendEmail {
to: String,
subject: String,
body: String,
}
impl TaskHandler for SendEmail {
const IDENTIFIER: &'static str = "send_email";
async fn run(self, _ctx: WorkerContext) -> impl IntoTaskHandlerResult {
println!("Sending email to {} with subject '{}'", self.to, self.subject);
// Actual email sending logic would go here
Ok::<(), String>(())
}
}Required Associated Constants§
Sourceconst IDENTIFIER: &'static str
const IDENTIFIER: &'static str
Unique identifier for this task type.
This identifier must be unique across all task types in your application. It is used to match incoming jobs to the correct handler.
§Best Practices
- Use lowercase snake_case names
- Make names descriptive but concise
- Ensure they are globally unique across your application
Required Methods§
Sourcefn run(
self,
ctx: WorkerContext,
) -> impl Future<Output = impl IntoTaskHandlerResult> + Send + 'static
fn run( self, ctx: WorkerContext, ) -> impl Future<Output = impl IntoTaskHandlerResult> + Send + 'static
Execute the task logic.
This method is called when a job of this task type is processed by the worker. It contains the actual business logic for processing the job.
§Arguments
self- The task payload, deserialized from the job’s JSON payloadctx- Worker context providing access to job metadata and extensions
§Returns
An async result that converts to a TaskHandlerResult, indicating success or failure.
- Return
Ok(())or just()for success - Return
Err(error)for failure, which will trigger retries
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.