docs.rs failed to build backbone-jobs-3.0.0
Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Backbone Jobs
A comprehensive job scheduling library for the Backbone Framework that provides robust cron-based task scheduling with PostgreSQL persistence and seamless integration with backbone-queue.
๐ Features
- Cron Expression Scheduling: Full support for standard 5-field cron expressions with timezone handling
- PostgreSQL Persistence: Reliable job storage with PostgreSQL as the primary database
- Queue Integration: Seamless integration with backbone-queue (Redis, RabbitMQ, AWS SQS)
- Job Lifecycle Management: Complete CRUD operations for scheduled jobs
- Retry Policies: Configurable retry mechanisms with exponential backoff
- Predefined Job Types: Built-in templates for common scheduling tasks
- Monitoring & Statistics: Comprehensive job execution tracking and metrics
- Builder Pattern: Flexible, type-safe configuration
- Async/Await: Full tokio async support for high-performance scheduling
- Error Handling: Robust error recovery and logging
๐ฆ Installation
Add to your Cargo.toml:
[]
= { = "0.1.0", = ["postgres", "redis"] }
= { = "1.0", = ["full"] }
= { = "0.4", = ["serde"] }
= "1.0"
= "0.1"
= "0.3"
Optional Features
postgres: PostgreSQL job storage (default)redis: Redis queue supportrabbitmq: RabbitMQ queue supportmonitoring: Enhanced monitoring capabilitiespg_cron: PostgreSQL pg_cron extension integration
๐โโ๏ธ Quick Start
use ;
use InMemoryJobStorage;
use json;
use Arc;
async
๐ Predefined Job Types
Backbone Jobs comes with several predefined job templates for common scenarios:
Using Predefined Jobs
use *;
// Daily database backup at 2 AM
let backup_job = daily_backup?;
// Weekly log cleanup on Sunday at 3 AM
let log_cleanup = weekly_log_cleanup?;
// Hourly data synchronization
let data_sync = hourly_data_sync?;
// Monthly analytics report
let monthly_report = monthly_report?;
// Session cleanup every 6 hours
let session_cleanup = session_cleanup?;
// Email campaigns on weekdays at 9 AM
let email_campaigns = email_campaign_schedule?;
// Database maintenance weekly on Sunday at 1 AM
let db_maintenance = database_maintenance?;
// Cache warming every 30 minutes
let cache_warming = cache_warming?;
// Schedule all jobs
scheduler.schedule_job.await?;
scheduler.schedule_job.await?;
scheduler.schedule_job.await?;
// ... schedule other jobs
Available Predefined Jobs
| Job Type | Schedule | Description |
|---|---|---|
daily_backup() |
0 2 * * * |
Daily database backup at 2 AM |
weekly_log_cleanup() |
0 3 * * 0 |
Weekly log cleanup on Sunday at 3 AM |
hourly_data_sync() |
0 * * * * |
Hourly data synchronization |
monthly_report() |
0 6 1 * * |
Monthly analytics report on 1st at 6 AM |
session_cleanup() |
0 */6 * * * |
Session cleanup every 6 hours |
email_campaign_schedule() |
0 9 * * 1-5 |
Email campaigns on weekdays at 9 AM |
database_maintenance() |
0 1 * * 0 |
Database maintenance weekly on Sunday at 1 AM |
cache_warming() |
*/30 * * * * |
Cache warming every 30 minutes |
๐ง Advanced Usage
Custom Job Configuration
use ;
use Duration;
let custom_job = new
.id
.name
.description
.cron // Every 15 minutes
.queue
.payload
.priority
.timeout // 1 hour timeout
.retry_policy // 3 retries, 5min start
.timezone
.max_attempts
.build?;
Scheduler Configuration
use ;
use Duration;
let config = SchedulerConfig ;
let scheduler = new
.with_config
.with_storage
.build?;
Job Lifecycle Management
// Schedule a job
let job = create_job?;
scheduler.schedule_job.await?;
// List all jobs
let jobs = scheduler.list_jobs.await?;
for job in jobs
// Get job by ID
let job = scheduler.get_job.await?;
// Update job
scheduler.update_job.await?;
// Pause a job
scheduler.pause_job.await?;
// Resume a paused job
scheduler.resume_job.await?;
// Cancel a job
scheduler.cancel_job.await?;
// Trigger immediate execution
scheduler.trigger_job.await?;
// Delete a job
scheduler.unschedule_job.await?;
Job Statistics and Monitoring
// Get scheduler statistics
let stats = scheduler.get_statistics.await?;
println!;
println!;
println!;
println!;
// Get job execution history
let history = scheduler.get_job_history.await?;
for attempt in history
๐ Cron Expressions
Backbone Jobs supports standard 5-field cron expressions:
* * * * *
โ โ โ โ โ
โ โ โ โ โโโโ Day of Week (0-7, Sunday=0 or 7)
โ โ โ โโโโโโ Month (1-12)
โ โ โโโโโโโโ Day of Month (1-31)
โ โโโโโโโโโโ Hour (0-23)
โโโโโโโโโโโโ Minute (0-59)
Common Patterns
| Pattern | Description |
|---|---|
* * * * * |
Every minute |
*/15 * * * * |
Every 15 minutes |
0 * * * * |
Every hour at minute 0 |
0 2 * * * |
Daily at 2 AM |
0 9 * * 1-5 |
Weekdays at 9 AM |
0 0 * * 0 |
Weekly on Sunday at midnight |
0 0 1 * * |
Monthly on 1st at midnight |
0 9-17 * * 1-5 |
Every hour from 9 AM to 5 PM on weekdays |
Advanced Examples
// Complex scheduling examples
let jobs = vec!;
๐ Retry Policies
Configure custom retry behavior for failed jobs:
use RetryPolicy;
use Duration;
// Exponential backoff with jitter
let exponential_retry = exponential
.with_max_delay
.with_jitter; // 10% jitter
// Fixed delay retries
let fixed_retry = fixed;
// Linear backoff
let linear_retry = linear;
// No retries
let no_retry = none;
// Apply to job
let job = new
.id
.name
.cron
.queue
.payload
.retry_policy
.build?;
๐๏ธ Storage Backends
In-Memory Storage (for testing)
use InMemoryJobStorage;
let storage = new;
let scheduler = new
.with_storage
.build?;
PostgreSQL Storage (production)
// PostgreSQL storage will be implemented with full feature support
// Including:
// - Connection pooling
// - Migration support
// - Transaction handling
// - Performance optimization
// - Backup/restore capabilities
// Example (coming soon):
let storage = new.await?;
let scheduler = new
.with_storage
.build?;
๐ Queue Integration
Redis Queue
use RedisQueueService;
use JobExecutor;
let queue_service = new;
let executor = new;
let scheduler = new
.with_storage
.with_executor
.build?;
RabbitMQ Queue
use RabbitMQQueueService;
let queue_service = new;
let executor = new;
AWS SQS Queue
use SqsQueueService;
let queue_service = new;
let executor = new;
๐ Error Handling
Backbone Jobs provides comprehensive error handling:
use JobError;
match scheduler.schedule_job.await
Error Types
JobError::JobAlreadyExists: Job with same ID already existsJobError::JobNotFound: Job not foundJobError::Validation: Job validation failedJobError::Execution: Job execution failedJobError::Storage: Storage operation failedJobError::Configuration: Configuration errorJobError::CronParse: Cron expression parsing failed
๐ Monitoring and Logging
Structured Logging
use ;
// Enable debug logging
fmt
.with_max_level
.init;
// Logs will include:
// - Job scheduling events
// - Execution start/completion
// - Retry attempts
// - Error details
// - Performance metrics
Custom Metrics
// Get real-time statistics
let stats = scheduler.get_statistics.await?;
// Export to monitoring systems
register_gauge!.set;
register_gauge!.set;
๐งช Testing
Unit Testing
Integration Testing
async
๐ข Production Deployment
Configuration
# application.yml
scheduler:
poll_interval: 30s
max_concurrent_jobs: 50
default_timeout: 1800s
default_timezone: "UTC"
cleanup_old_attempts: true
cleanup_attempts_older_than_days: 30
database:
url: "postgresql://user:pass@localhost/backbone_jobs"
max_connections: 20
min_connections: 5
queue:
type: "redis" # redis, rabbitmq, sqs
url: "redis://localhost:6379"
monitoring:
enabled: true
metrics_port: 9090
health_check_interval: 30s
Docker Deployment
FROM rust:1.75 as builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/your-app /usr/local/bin/
EXPOSE 3000
CMD ["your-app"]
Kubernetes Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: backbone-jobs-scheduler
spec:
replicas: 2
selector:
matchLabels:
app: backbone-jobs-scheduler
template:
metadata:
labels:
app: backbone-jobs-scheduler
spec:
containers:
- name: scheduler
image: your-app:latest
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: url
- name: REDIS_URL
value: "redis://redis:6379"
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
๐ง Best Practices
Job Design
- Idempotent Jobs: Design jobs to be safe to run multiple times
- Time Limits: Set appropriate timeouts to prevent hanging jobs
- Retry Strategies: Use exponential backoff for transient failures
- Monitoring: Log important events and metrics
- Resource Limits: Consider memory and CPU usage for batch jobs
Cron Expressions
- Test Before Deploy: Use online cron testers to verify expressions
- Timezone Awareness: Always specify timezones for distributed systems
- Avoid Overlap: Space out resource-intensive jobs
- Maintenance Windows: Schedule heavy tasks during low-traffic periods
Performance
- Batch Processing: Process items in batches rather than one-by-one
- Connection Pooling: Use database connection pools
- Async Operations: Use async/await for I/O operations
- Monitoring: Track job execution times and success rates
๐ Examples
See the examples/ directory for comprehensive examples:
basic_scheduler.rs- Basic scheduler setup and job schedulingcron_jobs.rs- Advanced cron patterns and real-world scenariosdatabase_cleanup.rs- Database maintenance automation
Running Examples
# Basic scheduler example
# Advanced cron patterns
# Database cleanup automation
๐ค Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Related Projects
- Backbone Queue - Message queue abstraction layer
- Backbone Framework - Complete framework documentation
- Backbone Framework Quick Start - Quick start guide
๐ Support
- Create an issue for bug reports or feature requests
- Check the examples directory for usage patterns
- Review the API documentation for detailed reference