12 unstable releases (3 breaking)

new 0.3.1 Dec 11, 2024
0.3.0 Dec 1, 2024
0.2.2 Oct 19, 2024
0.2.0 Sep 28, 2024
0.0.8 Aug 25, 2024

#304 in Date and time

Download history 258/week @ 2024-08-19 44/week @ 2024-08-26 340/week @ 2024-09-02 51/week @ 2024-09-09 38/week @ 2024-09-16 90/week @ 2024-09-23 161/week @ 2024-09-30 74/week @ 2024-10-07 144/week @ 2024-10-14 26/week @ 2024-10-21 13/week @ 2024-10-28 1/week @ 2024-11-18 120/week @ 2024-11-25 63/week @ 2024-12-02

184 downloads per month

MIT license

82KB
2K SLoC

crates.io Documentation

Dependencies

spring-job = { version = "<version>" }

API interface

App implements the JobConfigurator feature, which can be used to configure the scheduling task:

use spring::App;
use spring_job::{cron, JobPlugin, JobConfigurator, Jobs};
use spring_sqlx::SqlxPlugin;

#[tokio::main]
async fn main() {
    App::new()
        .add_plugin(JobPlugin)
        .add_plugin(SqlxPlugin)
        .add_jobs(jobs())
        .run()
        .await
}

fn jobs() -> Jobs {
    Jobs::new().typed_job(cron_job)
}

#[cron("1/10 * * * * *")]
async fn cron_job() {
    println!("cron scheduled: {:?}", SystemTime::now())
}

You can also use the auto_config macro to implement automatic configuration. This process macro will automatically register the scheduled tasks marked by the Procedural Macro into the app:

+#[auto_config(JobConfigurator)]
 #[tokio::main]
 async fn main() {
    App::new()
    .add_plugin(JobPlugin)
    .add_plugin(SqlxPlugin)
-   .add_jobs(jobs())
    .run()
    .await
}

Extract the Component registered by the plugin

The SqlxPlugin plugin above automatically registers a Sqlx connection pool component for us. We can use Component to extract this connection pool from App. It should be noted that although the implementation principles of spring-job's Component and spring-web's Component are similar, these two extractors belong to different crates.

use spring_sqlx::{
    sqlx::{self, Row}, ConnectPool
};
use spring_job::cron;
use spring_job::extractor::Component;

#[cron("1/10 * * * * *")]
async fn cron_job(Component(db): Component<ConnectPool>) {
    let time: String = sqlx::query("select DATE_FORMAT(now(),'%Y-%m-%d %H:%i:%s') as time")
        .fetch_one(&db)
        .await
        .context("query failed")
        .unwrap()
        .get("time");
    println!("cron scheduled: {:?}", time)
}

Read configuration

You can use Config to extract the configuration in toml. The usage is exactly the same as spring-web.

#[derive(Debug, Configurable, Deserialize)]
#[config_prefix = "custom"]
struct CustomConfig {
    a: u32,
    b: bool,
}

#[cron("1/10 * * * * *")]
async fn use_toml_config(Config(conf): Config<CustomConfig>) -> impl IntoResponse {
    format!("a={}, b={}", conf.a, conf.b)
}

Add the corresponding configuration to your configuration file:

[custom]
a = 1
b = true

Dependencies

~13–23MB
~317K SLoC