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

如何通过Cron定期调用Fastify指定路由?

使用fastify-cron定期调用Fastify内部路由解决方案

你可以通过fastify-cron轻松实现定期调用Fastify路由,有两种高效的实现方式,根据你的需求选择即可:

方式一:直接调用路由处理函数(性能优先)

如果你的路由逻辑不需要完整的HTTP上下文,直接抽离并调用处理函数是最优选择,无需经过HTTP请求层:

// 抽离路由处理逻辑,方便复用
const handleGreeting = (request, reply) => {
  reply.send({ hello: 'world' })
}

// 注册路由
fastify.get('/greeting', handleGreeting)

// 配置fastify-cron定时任务
fastify.register(require('fastify-cron'), {
  jobs: [
    {
      cronTime: '0 0 * * *', // 每天午夜执行的cron表达式
      onTick: () => {
        // 按需构造request和reply对象(如果处理函数依赖参数)
        const mockReq = {}
        const mockReply = {
          send: (data) => {
            console.log('定时任务执行结果:', data)
            // 可添加日志、持久化等后续处理
          }
        }
        handleGreeting(mockReq, mockReply)
      },
      start: true // 插件启动时立即启用任务
    }
  ]
})

方式二:用fastify.inject()模拟完整请求(流程完整)

如果需要经过Fastify的中间件、路由验证等完整请求链路,使用inject()方法模拟外部HTTP请求更合适:

fastify.get('/greeting', function (request, reply) {
  reply.send({ hello: 'world' })
})

// 配置fastify-cron定时任务
fastify.register(require('fastify-cron'), {
  jobs: [
    {
      cronTime: '0 0 * * *',
      onTick: async () => {
        try {
          const response = await fastify.inject({
            method: 'GET',
            url: '/greeting'
          })
          console.log('定时任务响应状态:', response.statusCode)
          console.log('定时任务响应内容:', response.json())
        } catch (err) {
          console.error('定时任务执行失败:', err)
        }
      },
      start: true
    }
  ]
})

两种方式对比

  • 直接调用处理函数:性能更高,适合逻辑独立、不需要HTTP上下文的场景
  • 使用inject():完全模拟真实请求流程,自动处理中间件和验证,适合需要完整请求上下文的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:36:33