7 releases

0.1.1 Sep 8, 2024
0.1.0 Sep 7, 2024
0.0.9 Sep 4, 2024
0.0.8 Aug 25, 2024

#568 in HTTP server

Download history 111/week @ 2024-08-04 117/week @ 2024-08-11 166/week @ 2024-08-18 166/week @ 2024-08-25 231/week @ 2024-09-01 178/week @ 2024-09-08

848 downloads per month

MIT license

53KB
1.5K SLoC

crates.io Documentation

Dependencies

spring-job = { version = "0.1.1" }

API interface

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

#[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)
}

Dependencies

~13–23MB
~318K SLoC