Node.js,Deno和浏览器的零依赖性cron解析器和调度程序。在NPM和JSR上发布
通过NPM:
$ npm install cron-schedule
通过纱线:
$ yarn add cron-schedule
通过PNPM:
$ pnpm add cron-schedule
20.12
18.20
。其他版本的node.js也可能起作用,但这没有测试。
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 >
上面的示例使用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
另外,您可以使用deno add @p4sca1/cron-schedule
,并从@p4sca1/cron-schedule
中导入,或从没有安装步骤的情况下从jsr:@p4sca1/cron-schedule
。
DENO Import和Skypack CDN URL包含A :version
占位符。替换:version
。支持SEMVER范围。始终使用最新的4.x
版本使用^4.0.0
。有关可用版本的列表,请参见https://www.npmjs.com/package/package/cron-schedule。
// 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
您可以根据CRON表达式安排要执行的任务。 Cron-Schedule配备了2个不同的调度程序。
如果使用Typescript,请确保将compilerOptions.moduleResolution
设置为node16
或nodenext
。
基于计时器的CRON调度程序为每个计划的CRON创建一个计时器。当节点超时限制超过约24天时,它会使用多个连续超时。
// 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
优点:
缺点:
基于间隔的调度程序以固定的间隔检查适当任务。因此,分配给调度程序的所有任务只有一个间隔。您可以有多个基于间隔的调度程序的实例。
// 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 ( )
优点:
缺点:
对于大多数人来说,基于计时器的调度程序应该是一个不错的选择。但是,Settimeout对于长时间延迟可能是不可靠的。当您遇到长时间 /间隔因许多计划任务而遇到性能问题的问题时,您应该考虑基于间隔的调度程序。
cron_schedule使用Linux cron语法,如下所述,您可以选择通过使用另一个字段来预定分钟字段来指定秒。
┌───────────── second (0 - 59, optional)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12)
│ │ │ │ │ ┌───────────── weekday (0 - 7)
* * * * * *
支持所有Linux cron功能,包括
对于简单的定时任务(例如每x秒),您应该考虑使用setInterval
,更适合简单的计时任务,因为它没有计算开销。
寻找一种方法来验证后端(node.js)或浏览器中有多个预设的浏览器中的cron表达式吗?查看cron validate!
使用npm-cron-schedule
预设来验证Cron-Schedule支持Cron表达式。