You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify 5中定时运行路由的推荐实现方式

Fastify5 中定期运行路由的几种方案

方案一:直接使用 node-cron 集成定时任务

fastify-cron 底层依赖的就是 node-cron,既然旧插件不兼容Fastify5,直接用原生库反而更轻量可控。

  1. 安装依赖
npm install node-cron
  1. 集成到Fastify应用
    通过Fastify的onReady钩子启动定时任务,用inject方法调用目标路由(模拟HTTP请求,和手动访问路由效果一致):
import cron from 'node-cron'
import Fastify from 'fastify'

const fastify = Fastify({ logger: true })

// 定义需要定时执行的路由
fastify.get('/weekly-job', async (request, reply) => {
  // 你的任务逻辑,比如数据同步、报表生成等
  await syncDataFromExternalAPI()
  return { status: 'completed' }
})

// 应用启动就绪后创建定时任务(每周日凌晨2点执行)
fastify.addHook('onReady', () => {
  cron.schedule('0 2 * * 0', async () => {
    try {
      const response = await fastify.inject({
        method: 'GET',
        url: '/weekly-job'
      })
      fastify.log.info(`Weekly job executed, response status: ${response.statusCode}`)
    } catch (err) {
      fastify.log.error('Weekly job failed:', err)
    }
  })
})

// 启动应用
const start = async () => {
  try {
    await fastify.listen({ port: 3000 })
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

方案二:抽离任务逻辑,直接调用函数(更高效)

如果不需要通过HTTP接口访问任务逻辑,直接抽离成独立函数定时调用,避免HTTP请求的额外开销:

import cron from 'node-cron'
import Fastify from 'fastify'

const fastify = Fastify({ logger: true })

// 抽离独立的任务函数
async function dailyCleanupTask() {
  fastify.log.info('Starting daily cleanup...')
  // 执行清理逻辑,比如删除过期数据
  await fastify.prisma.oldRecords.deleteMany({
    where: { createdAt: { lt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) } }
  })
  fastify.log.info('Daily cleanup completed')
}

// 可选:挂载为路由,支持手动触发
fastify.get('/daily-cleanup', async () => {
  await dailyCleanupTask()
  return { status: 'success' }
})

// 定时执行任务(每日凌晨1点)
fastify.addHook('onReady', () => {
  cron.schedule('0 1 * * *', dailyCleanupTask)
})

// 启动应用...

方案三:使用兼容Fastify5的社区插件

如果偏好Fastify插件的集成方式,可以尝试@fastify/schedule(社区维护的定时任务插件,适配Fastify最新版本),用法和fastify-cron类似:

  1. 安装依赖
npm install @fastify/schedule
  1. 集成示例
import Fastify from 'fastify'
import fastifySchedule from '@fastify/schedule'
import cron from 'node-cron'

const fastify = Fastify({ logger: true })
await fastify.register(fastifySchedule)

// 添加定时任务
fastify.scheduler.addCronJob('daily-job', cron.schedule('0 1 * * *', async () => {
  await fastify.inject({ method: 'GET', url: '/daily-job' })
  fastify.log.info('Daily job executed')
}))

// 定义路由...

内容的提问来源于stack exchange,提问作者punkish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 02:31:20