P4sca1 / cron-schedule

A zero-dependency cron parser and scheduler for Node.js, Deno and the browser.
MIT License
177 stars 15 forks source link

Confusion on Scheduling a Cron Task #281

Closed radiantone closed 2 years ago

radiantone commented 2 years ago

Hi, I don't see in the Readme how to schedule a task that repeats based on a CRON string. I tried to schedule a task to run every 5 seconds. But it doesn't really work. It runs once only. It says there are only two schedulers , timeout and interval. But I don't want either, I want a schedular to run a task continously based on a cron string. Just like cron. What's the secret?

import { parseCronExpression, TimerBasedCronScheduler as scheduler } from 'cron-schedule' const cron = parseCronExpression('/5 *')

scheduler.setTimeout(cron, () => { // This doesn't feel right, but also only runs once console.log(new Date(), 'TASK EXECUTED') })

P4sca1 commented 1 year ago

scheduler.setInterval is what you are looking for.

import { parseCronExpression, TimerBasedCronScheduler as scheduler } from 'cron-schedule'
const cron = parseCronExpression('*/5 * * * *')

scheduler.setInterval(cron, () => {
  console.log(new Date(), 'TASK EXECUTED')
})

However, for such a simple timing task, you might want to use a simple setInterval(() => {}, 5000).