Search code examples
cronfastify

running a fastify route periodically (via cron)


I would like to run a particular fastify route periodically. There is fastify-cron but I can't figure out if I can use that to call a route from within fastify. To summarize, given a route as below, I would like https://my/server/greeting to be called every midnight.

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

Solution

  • By using that plugin you can use the inject method, used to write tests typically:

    import Fastify from 'fastify'
    import fastifyCron from 'fastify-cron'
    
    const server = Fastify()
    
    server.get('/greeting', function (request, reply) {
      reply.send({ hello: 'world' })
    })
    
    server.register(fastifyCron, {
      jobs: [
        {
          cronTime: '0 0 * * *', // Everyday at midnight UTC
          onTick: async server => {
            try {
              const response = await server.inject('/greeting')
              console.log(response.json())
            } catch (err) { console.error(err) }
          }
        }
      ]
    })
    
    server.listen(() => {
      // By default, jobs are not running at startup
      server.cron.startAllJobs()
    })
    

    This is needed because you need to generate e request/response object to run your handler.