定时任务

需要每隔几秒或每天固定时刻自动跑后台逻辑时,给 Task 配一条 Cron 计划即可。本篇每 5 秒触发一次心跳任务,并在 /metrics 接口查看自动累加的计数。

架构图示

写代码#

第 1 步:新建 Cargo.toml(默认在内存里运行任务和定时计划):

TOML
[package]
name = "guide-cron"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"

[dependencies]
kxed = "0.0.5-alpha"

第 2 步:新建 src/jobs.rs,定义一个每次执行把计数器加 1 的后台任务:

Rust
use kxed::prelude::*;

#[derive(Serialize, Deserialize)]
pub(crate) struct Heartbeat;

#[task]
impl NormalTask for Heartbeat {
    async fn run(self, _: &TaskCtx) -> Result<(), AppErr> {
        kxed::metrics::counter!("chat_heartbeats_total").increment(1);
        Ok(())
    }
}

第 3 步:把 Heartbeat 绑到每 5 秒一次的计划上,写 src/main.rs:

Rust
mod jobs;

use kxed::prelude::*;

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new().cron("0/5 * * * * *", jobs::Heartbeat).run().await
}
  • 复用 Task 执行链:每次到点会自动提交一条新 Heartbeat 任务,重试、超时和监控规则与手动 ctx.submit 完全一致。
  • 开箱即用的指标:kxed::metrics 里的 counter!、gauge!、histogram! 会直接输出到 /metrics 接口,不用额配采集器。

验证#

先运行 cargo run,再另开终端等待 7 秒后读取指标(约定见 怎么读):

Shell
sleep 7
curl --silent http://127.0.0.1:8080/metrics | grep '^chat_heartbeats_total'

预期输出(<n> 随运行时长增加,至少为 1):

输出
chat_heartbeats_total <n>

不用发任何外部请求,后台每 5 秒自动跑一次 Heartbeat,过几秒再查 /metrics 数字会继续往上涨。

在线运行#

官网实时示例用六段表达式 0 * * * * * 每逢整分触发一次心跳,页面实时显示最近一次触发时刻与下次倒计时:

实时交互沙盒cron/heartbeat
每分钟整点触发0 * * * * *

正在读取计划的触发记录...

查看后端实现源码(Rust)折叠 / 展开
Rust
/// 六段表达式,第一段是秒:每分钟的第 0 秒触发,`demos::backend` 里 `App::new().cron(SCHEDULE, Heartbeat)`。
pub const SCHEDULE: &str = "0 * * * * *";

#[derive(Serialize, Deserialize)]
pub struct Heartbeat;

#[task]
impl NormalTask for Heartbeat {
    async fn run(self, ctx: &TaskCtx) -> Result<(), AppErr> {
        ctx.require_state::<Live>()?.pulse.fire(SystemTime::now());
        Ok(())
    }
}

表达式#

计划可以直接传字符串,也可以用构造器生成(格式写错会在 config check 和启动时报错):

写法示例触发时机与规则
"0 9 * * 1-5"5 段(分 时 日 月 周):工作日 9:00,周字段用数字(0 和 7 都代表周日)
"0/5 * * * * *"6 段(秒 分 时 日 月 周):每 5 秒一次;6 段和 7 段的星期必须写 SUN 到 SAT 英文缩写
"CRON_TZ=Asia/Shanghai 0 9 * * 1-5"带时区前缀:按北京时间排程;夏令时拨快跳过的时刻不补,拨回重复的时刻只跑一次
CronSchedule::daily_at(9, 30)?固定时刻构造器(另有 hourly_at(15)?、weekly_at(1, 8, 0)?),按 UTC 计算,1 至 7 为周一到周日
  • 日与周不同时限定:同一条表达式不能既指定几号又指定星期几(如 "0 0 1,15 * 1" 会被拒绝),需要「满足其一就跑」时拆成两条 .cron(..) 即可。

登记计划与开关#

  • 同一个任务排多套时间表:App::cron(schedule, task) 默认用任务名做计划名;同一个任务要挂多个时间表时改用 App::cron_named(name, schedule, task)(见 task-queues 示例 与 TASK 第 5 节)。
  • 按实例角色开关:多实例部署时可单独控制哪些实例负责排程、哪些负责跑任务:
配置项默认值设为 false 后的效果
tasks.scheduling.enabledtrue本实例不扫描时间表,交由集群其他实例触发
tasks.execution.enabledtrue本实例只接请求,不执行后台任务

停机积压与重叠#

开启持久化任务存储(如 task-sqlite)后,可以定制「服务停机恢复后要不要补跑」以及「上次还没跑完下次又到点怎么办」:

策略写法行为
默认 CronMisfire::Latest停机错过的多次触发合并成一次,恢复后只补跑最后一次
.with_misfire(CronMisfire::CatchUp)把停机期间错过的每一次都逐个补跑(高频计划开启会在启动时打告警)
.with_misfire(CronMisfire::Skip)超过 tasks.cron.misfire_grace 宽限期的积压直接跳过
默认 CronOverlap::Allow上一次还没跑完也照常触发新任务
.with_overlap(CronOverlap::Skip)上一次还在跑就跳过本次
.with_overlap(CronOverlap::Queue)等上一次跑完后,再按积压策略补跑

比如每小时对账一次、一期都不能漏、上次没跑完就排队等待:

Rust
App::new().cron(
    CronSchedule::parse("0 0 * * * *")?
        .with_misfire(CronMisfire::CatchUp)
        .with_overlap(CronOverlap::Queue),
    jobs::Report,
)
  • 测试里快进时间:调用 app.clock().travel(..) 后执行 app.sync_cron_clock().await 同步计划游标(需持久化存储),再调 app.drain_tasks().await 等待任务跑完。

更换或取消计划#

  • 代码声明的计划自动同步:改了 App::cron 的时间表或删掉代码后重新发版,新进程启动时会自动更新或取消数据库里的原有计划;滚动升级期间,较低代次的进程不会反向覆盖新代次的计划(回退上一版本二进制需恢复计划时可设 tasks.cron.generation)。
  • 运行时动态计划:ctx.schedule_cron(schedule, task) 创建的匿名计划不会随发版自动清理,需要保存返回的 CronHandle 调 .cancel().await?,或分页查出后取消:
Rust
async fn cancel_stale_heartbeats(ctx: AppCtx) -> Result<(), AppErr> {
    let mut after = None;
    loop {
        let page = ctx.cron_schedules::<jobs::Heartbeat>(after, 256).await?;
        let Some(last) = page.last() else {
            return Ok(());
        };
        after = Some(last.id);
        for schedule in page {
            if schedule.name.is_none() {
                ctx.lookup_cron::<jobs::Heartbeat>(schedule.id).await?.cancel().await?;
            }
        }
    }
}
  • 命令行查看与手动触发:运行 ./app cron list 查看所有计划状态,运行 ./app cron run <schedule> 可立即手动跑一次而不打乱原定时间表(见 运维命令)。

清理业务数据#

登录日志、审计流水这类只增不减的表,通常每天凌晨用 Cron 分批清理过期记录,并把同一个清理函数挂成命令行工具方便随时手动执行(带 deleted_at 的软删除表可直接用 audit::prune_deleted)。

第 1 步:引入 SQLite 与迁移支持,Cargo.toml 的完整内容是:

TOML
[package]
name = "guide-cron"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"

[dependencies]
kxed = { version = "0.0.5-alpha", features = ["seaorm-sqlite", "seaorm-migration"] }

第 2 步:新建 config/database.toml:

TOML
url = "sqlite://guide-cron.sqlite?mode=rwc"

第 3 步:新建 src/login_attempt.rs,建表并实现每次最多删 1000 行的 purge 函数(先查主键再按主键删,跨数据库兼容且不会长时间锁表):

Rust
use kxed::plugins::seaorm::async_trait;
use kxed::plugins::seaorm::sea_orm::entity::prelude::*;
use kxed::plugins::seaorm::sea_orm::sea_query::Table;
use kxed::plugins::seaorm::sea_orm::{self, DbErr, QueryOrder, QuerySelect, Schema};
use kxed::plugins::seaorm::sea_orm_migration::{MigrationName, MigrationTrait, MigratorTrait, SchemaManager};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

pub(crate) const BATCH: u64 = 1000;

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "login_attempts")]
pub(crate) struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    pub account: String,
    pub created_at: i64,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub(crate) enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

/// 删除 `retention` 之前的记录,返回删除的行数。
pub(crate) async fn purge(db: &DatabaseConnection, retention: Duration) -> Result<u64, DbErr> {
    let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_secs());
    let cutoff = now.saturating_sub(retention.as_secs()) as i64;
    let mut deleted = 0;
    loop {
        let ids: Vec<i64> = Entity::find()
            .select_only()
            .column(Column::Id)
            .filter(Column::CreatedAt.lt(cutoff))
            .order_by_asc(Column::Id)
            .limit(BATCH)
            .into_tuple()
            .all(db)
            .await?;
        let last_batch = (ids.len() as u64) < BATCH;
        if !ids.is_empty() {
            deleted += Entity::delete_many().filter(Column::Id.is_in(ids)).exec(db).await?.rows_affected;
        }
        if last_batch {
            return Ok(deleted);
        }
    }
}

pub(crate) struct Migrator;

#[async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        vec![Box::new(CreateLoginAttempts)]
    }
}

struct CreateLoginAttempts;

impl MigrationName for CreateLoginAttempts {
    fn name(&self) -> &str {
        "m20261120_000001_create_login_attempts"
    }
}

#[async_trait]
impl MigrationTrait for CreateLoginAttempts {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let schema = Schema::new(manager.get_database_backend());
        manager.create_table(schema.create_table_from_entity(Entity)).await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager.drop_table(Table::drop().table(Entity).to_owned()).await
    }
}

第 4 步:新建 src/cleanup.rs,把 purge 同时包装成定时任务与手工命令(require_shared 会拦截内存库,确保命令与服务连的是同一个库):

Rust
use crate::login_attempt;
use kxed::command::Record;
use kxed::plugins::seaorm::DatabaseCapability;
use kxed::prelude::*;
use std::time::Duration;

const RETENTION: Duration = Duration::from_secs(30 * 86_400);

#[derive(Serialize, Deserialize)]
pub(crate) struct PurgeLoginAttempts;

#[task]
impl NormalTask for PurgeLoginAttempts {
    async fn run(self, ctx: &TaskCtx) -> Result<(), AppErr> {
        let deleted = login_attempt::purge(&*ctx.db()?, RETENTION).await?;
        kxed::tracing::info!(deleted, "purged login attempts");
        Ok(())
    }
}

/// 立即清理 30 天前的登录记录。
#[derive(Command)]
#[command(name = "login-attempts purge")]
pub(crate) struct PurgeNow;

impl Command for PurgeNow {
    async fn run(self, ctx: &AppCtx) -> Result<Output, AppErr> {
        DatabaseCapability::require_shared(ctx)?;
        let deleted = login_attempt::purge(&*ctx.db()?, RETENTION).await?;
        Ok(Record::new().field("deleted", deleted).into())
    }
}

第 5 步:注册数据库插件与凌晨 3 点的清理计划,src/main.rs 的完整内容是:

Rust
mod cleanup;
mod jobs;
mod login_attempt;
#[cfg(test)]
mod tests;

use kxed::plugins::seaorm::{MigrationLock, SeaOrmPlugin};
use kxed::prelude::*;

#[kxed::main]
async fn main() -> kxed::Result<()> {
    App::new()
        .plugin(SeaOrmPlugin::new().migrate::<login_attempt::Migrator>(MigrationLock::new("guide-cron.migrations")))
        .cron("0/5 * * * * *", jobs::Heartbeat)
        .cron("0 0 3 * * *", cleanup::PurgeLoginAttempts)
        .run()
        .await
}

第 6 步:新建 src/tests.rs,测试单批与跨批删除都只删过期行、保留新记录:

Rust
use crate::login_attempt::{ActiveModel, BATCH, Entity, Migrator, purge};
use kxed::plugins::seaorm::sea_orm::{ActiveValue::Set, Database, EntityTrait, PaginatorTrait};
use kxed::plugins::seaorm::sea_orm_migration::MigratorTrait;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[kxed::tokio::test]
async fn purge_deletes_every_batch_and_keeps_fresh_rows() {
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
    for expired in [BATCH, BATCH + 37] {
        let db = Database::connect("sqlite::memory:").await.unwrap();
        Migrator::up(&db, None).await.unwrap();
        let ages = (0..expired).map(|_| 40 * 86_400).chain([0; 5]);
        let rows = ages.map(|age| ActiveModel { account: Set("alice".into()), created_at: Set(now - age), ..Default::default() });
        Entity::insert_many(rows).exec(&db).await.unwrap();
        assert_eq!(purge(&db, Duration::from_secs(30 * 86_400)).await.unwrap(), expired);
        assert_eq!(Entity::find().count(&db).await.unwrap(), 5);
    }
}

运行 cargo test 验证分批逻辑;服务启动建好表后,也可以随时手工执行清理命令:

Shell
cargo run -- login-attempts purge

预期输出:

输出
deleted  0

常见排错#

现象原因解决方法
启动提示 Cron 表达式不合法6 段带秒表达式里的星期写了数字,或同一条表达式同时指定了几号与星期几6 段表达式星期改用 MON 到 SUN 缩写;日与周「满足其一」拆成两条 cron_named
单测里 clock().travel(..) 后定时任务没跑持久 Cron 游标需要先同步虚拟时钟偏移才会产出到期任务travel 后依次调用 app.sync_cron_clock().await 与 app.drain_tasks().await
删掉 ctx.schedule_cron 代码后旧计划仍在触发运行期动态创建的匿名计划存放在数据库中,不随发版自动清除用 ctx.cron_schedules::<T> 查出匿名计划后调 .cancel().await? 清理

参考#