Crate cronline

Crate cronline 

Source
Expand description

§Cronline: Lightweight Task Scheduling for Rust

Cronline is a minimalist yet powerful cron-style task scheduler built with Rust. Designed for simplicity, performance, and ease of integration, it enables developers to effortlessly manage scheduled asynchronous tasks within Rust applications.

§Features

  • Cron-like Scheduling: Intuitive scheduling using standard cron syntax
  • Interval-based Scheduling: Simple interval-based task execution
  • Async-Await Native: First-class async task support leveraging Tokio
  • Robust Error Handling: Configurable retries and timeout handling
  • Task Statistics: Built-in execution tracking and metrics
  • Pause/Resume: Dynamic task control without stopping the scheduler
  • Task Tags/Labels: Organize and filter tasks using tags
  • Graceful Cancellation: Cancel running tasks cleanly
  • Timeout Warnings: Get warned at 80% of timeout duration
  • Event Bus: Subscribe to scheduler and task lifecycle events
  • Auto-generated Names: Meaningful task names from cron expressions
  • Thread-Safe: All components are safe to share across threads

§Quick Start

Add Cronline to your Cargo.toml:

[dependencies]
cronline = "0.2.1"
tokio = { version = "1", features = ["full"] }

§Basic Example

use cronline::{Scheduler, Task};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a new scheduler
    let scheduler = Scheduler::new();

    // Add a task that runs every hour at minute 0
    scheduler.add("0 * * * *", Task::new(|| async {
        println!("Running hourly task!");
        Ok(())
    }).with_name("Hourly Task")).await?;

    // Start the scheduler
    scheduler.start().await?;

    // Let it run for a while
    tokio::time::sleep(tokio::time::Duration::from_secs(3600)).await;

    // Stop the scheduler gracefully
    scheduler.stop().await?;

    Ok(())
}

§Advanced Usage

use cronline::{Scheduler, Task, TaskConfig, SchedulerConfig};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create scheduler with custom configuration
    let scheduler = Scheduler::with_config(SchedulerConfig {
        check_interval: Duration::from_millis(100),
        continue_on_error: true,
        shutdown_grace_period: Duration::from_secs(10),
    });

    // Subscribe to events
    let mut events = scheduler.event_bus().subscribe();
    tokio::spawn(async move {
        while let Ok(event) = events.recv().await {
            println!("Event: {:?}", event);
        }
    });

    // Add task with custom configuration
    scheduler.add("*/5 * * * *", Task::new(|| async {
        // Your task logic here
        Ok(())
    })
    .with_name("Custom Task")
    .with_tags(&["backup", "critical"])
    .with_config(TaskConfig {
        timeout: Some(Duration::from_secs(30)),
        max_retries: 3,
        retry_delay: Duration::from_secs(5),
        fail_scheduler_on_error: false,
    })).await?;

    // Add interval-based task
    scheduler.add_task(Task::new(|| async {
        println!("Running every 5 minutes!");
        Ok(())
    })
    .with_interval(Duration::from_secs(300))
    .with_tag("monitoring")).await?;

    scheduler.start().await?;

    // Filter tasks by tag
    let critical_tasks = scheduler.tasks_with_tag("critical").await;
    println!("Found {} critical tasks", critical_tasks.len());

    // Do other work...

    scheduler.stop().await?;
    Ok(())
}

§Cron Expression Syntax

Cronline uses standard cron syntax: * * * * * (minute, hour, day of month, month, day of week)

Examples:

  • * * * * * - Every minute
  • 0 * * * * - Every hour at minute 0
  • 0 0 * * * - Every day at midnight
  • 0 12 * * MON-FRI - Weekdays at noon
  • */15 * * * * - Every 15 minutes

§Main Components

  • Scheduler - Manages and executes tasks on a schedule
  • Task - Represents a schedulable asynchronous task
  • CronlineError - Error types for the library
  • Result - Convenient result type alias

Re-exports§

pub use crate::errors::CronlineError;
pub use crate::events::EventBus;
pub use crate::events::SchedulerEvent;
pub use crate::scheduler::Scheduler;
pub use crate::scheduler::SchedulerConfig;
pub use crate::task::ScheduleType;
pub use crate::task::Task;
pub use crate::task::TaskConfig;
pub use crate::task::TaskStats;
pub use crate::task::TaskStatus;

Modules§

errors
Error types for Cronline operations.
events
Event system for task and scheduler events.
scheduler
Scheduler for managing and executing tasks.
task
Task management and execution.

Constants§

VERSION
The version of the Cronline library.

Type Aliases§

Result
Convenient result type alias for Cronline operations.