Um analisador cron de dependência zero e agendador para Node.js, Deno e The Browser. Publicado no NPM e JSR
Via npm:
$ npm install cron-schedule
Via Yarn:
$ yarn add cron-schedule
Via PNPM:
$ pnpm add cron-schedule
Testamos nosso código contra os seguintes lançamentos Node.js ( 18.20
, 20.12
). Outras versões do Node.js também podem funcionar, mas isso não é testado.
import { parseCronExpression } from 'cron-schedule'
const cron = parseCronExpression ( '*/5 * * * *' )
console . log ( cron . getNextDate ( new Date ( 2020 , 10 , 20 , 18 , 32 ) ) )
// 2020-11-20T17:35:00.000Z
< script type =" module " >
import { parseCronExpression } from 'https://cdn.skypack.dev/cron-schedule@:version'
const cron = parseCronExpression ( '*/5 * * * *' )
console . log ( cron . getNextDate ( new Date ( 2020 , 10 , 20 , 18 , 32 ) ) )
// 2020-11-20T17:35:00.000Z
</ script >
Os exemplos acima usam Skypack.
import { parseCronExpression } from 'npm:cron-schedule@:version'
const cron = parseCronExpression ( '*/5 * * * *' )
console . log ( cron . getNextDate ( new Date ( 2020 , 10 , 20 , 18 , 32 ) ) )
// 2020-11-20T17:35:00.000Z
Como alternativa, você pode usar deno add @p4sca1/cron-schedule
e importar de @p4sca1/cron-schedule
, ou importar de jsr:@p4sca1/cron-schedule
sem uma etapa de instalação.
Os URLs de Deno Import e Skypack CDN contêm um espaço reservado :version
. Substitua :version
pela versão desejada. As faixas de semver são suportadas. Para sempre usar a versão 4.x
mais recente use ^4.0.0
. Consulte https://www.npmjs.com/package/cron-schedule para obter uma lista de versões disponíveis.
// Import method to parse a cron expression.
import { parseCronExpression } from 'cron-schedule'
// Parse a cron expression to return a Cron instance.
const cron = parseCronExpression ( '*/5 * * * *' )
// Get the next date starting from the given start date or now.
cron . getNextDate ( startDate ?: Date ) : Date
// Get the specified amount of future dates starting from the given start date or now.
cron . getNextDates ( amount : number , startDate ?: Date ) : Date [ ]
// Get an ES6 compatible iterator which iterates over the next dates starting from startDate or now.
// The iterator runs until the optional endDate is reached or forever.
// The advantage of an iterator is that you can get more further dates on demand by using iterator.next().
cron . getNextDatesIterator ( startDate : Date = new Date ( ) , endDate ?: Date ) : Generator < Date , undefined , undefined >
// Get the previou date starting from the given start date or now.
cron . getPrevDate ( startDate : Date = new Date ( ) ) : Date
// Get the specified amount of previous dates starting from the given start date or now.
cron . getPrevDates ( amount : number , startDate ?: Date ) : Date [ ]
// Get an ES6 compatible iterator which iterates over the previous dates starting from startDate or now.
// The iterator runs until the optional endDate is reached or forever.
// The advantage of an iterator is that you can get more previous dates on demand by using iterator.next().
cron . getPrevDatesIterator ( startDate : Date = new Date ( ) , endDate ?: Date ) : Generator < Date , undefined , undefined >
// Check whether there is a cron date at the given date.
cron . matchDate ( date : Date ) : boolean
Você pode agendar tarefas a serem executadas com base em uma expressão de Cron. O Cron-Schedule vem com 2 agendadores diferentes.
Se você usar o TypeScript, definir compilerOptions.moduleResolution
como node16
ou nodenext
.
O cronista baseado no timer cria um temporizador para cada cron programado. Quando o limite de tempo limite do nó de ~ 24 dias seria excedido, ele usa vários tempo limite consecutivo.
// Import the scheduler.
import { TimerBasedCronScheduler as scheduler } from 'cron-schedule/schedulers/timer-based.js'
// Create a timeout, which fill fire the task on the next cron date.
// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected.
// Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.
scheduler . setTimeout ( cron : Cron , task : ( ) = > unknown , opts ?: { errorHandler ?: ( err : Error ) = > unknown } ) : ITimerHandle
// Create an interval, which will fire the given task on every future cron date.
// This uses consecutive calls to scheduler.setTimeout under the hood.
// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected.
// The task remains scheduled when an error occurs.
// Returns a handle which can be used to clear the timeout using clearTimeoutOrInterval.
scheduler . setInterval ( cron : Cron , task : ( ) = > unknown , opts ?: { errorHandler ?: ( err : Error ) = > unknown } ) : ITimerHandle
// Clear a timeout or interval, making sure that the task will no longer execute.
scheduler . clearTimeoutOrInterval ( handle : ITimerHandle ) : void
Prós:
Contras:
O agendador baseado em intervalo verifica a devida tarefa em um intervalo fixo. Portanto, existe apenas um intervalo para todas as tarefas atribuídas a um agendador. Você pode ter várias instâncias de um agendador baseado em intervalo.
// Import the scheduler.
import { IntervalBasedCronScheduler } from 'cron-schedule/schedulers/interval-based.js'
// Instantiate a new instance of the scheduler with the given interval. In this example, the scheduler would check every 60 seconds.
const scheduler = new IntervalBasedCronScheduler ( 60 * 1000 )
// Register a new task that will be executed on every future cron date, or only on the next cron date if isOneTimeTask is true.
// An optional errorHandler can be provided, which is called when the task throws an error or returns a promise that gets rejected.
// The task remains scheduled when an error occurs (if not a one time task). Tasks are at max executed only once per interval.
// Returns an id to be used with unregisterTask.
scheduler . registerTask ( cron : Cron , task : ( ) = > unknown , opts ?: { isOneTimeTask ?: boolean , errorHandler ?: ( err : Error ) = > unknown } ) : number
// Unregister a task causing it to no longer be executed.
scheduler . unregisterTask ( id : number ) : void
// You can stop the scheduler, which clears the interval.
scheduler . stop ( )
// You can start the scheduler after stopping it again. A newly created scheduler is started by default.
// Tasks that were due while the scheduler was stopped will be executed on the next interval tick (but only a single time).
scheduler . start ( )
Prós:
Contras:
Para a maioria das pessoas, o agendador baseado no timer deve ser uma boa opção. No entanto, o setTimeout pode não ser confiável por longos atrasos. Quando você tem problemas com longos tempo limite / intervalos sendo ignorados ou problemas de desempenho por causa de muitas tarefas programadas, considere o agendador baseado em intervalo.
O CRON_SCHEDULE usa a sintaxe do Linux Cron, conforme descrito aqui com a adição que você pode especificar opcionalmente segundos, prévia o campo minuto com outro campo.
┌───────────── second (0 - 59, optional)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12)
│ │ │ │ │ ┌───────────── weekday (0 - 7)
* * * * * *
Todos os recursos do Linux Cron são suportados, incluindo
Para tarefas de tempo simples, como a cada x segundos, considere usar setInterval
, o que é mais adequado para tarefas de tempo simples, pois não possui a sobrecarga de cálculo.
Procurando uma maneira de validar expressões cron no seu back -end (node.js) ou no navegador com suporte para várias predefinições? Confira Cron-Validate!
Use a predefinição npm-cron-schedule
para validar que as expressões cron são suportadas pelo cron-schedule .