node.js、deno、およびブラウザのゼロ依存性クロンパーサーとスケジューラ。 NPMとJSRで公開されています
NPM経由:
$ npm install cron-schedule
糸経由:
$ yarn add cron-schedule
PNPM経由:
$ pnpm add cron-schedule
次のnode.jsリリース( 18.20
)に対してコードを20.12
します。 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/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-Scheduleには2つの異なるスケジューラが付属しています。
TypeScriptを使用する場合は、 compilerOptions.moduleResolution
node16
またはnodenext
に設定するようにしてください。
タイマーベースのCronスケジューラは、スケジュールされたクロンごとに1つのタイマーを作成します。 〜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
長所:
短所:
間隔ベースのスケジューラは、固定間隔で適切なタスクをチェックします。したがって、スケジューラに割り当てられたすべてのタスクの間隔は1つだけです。インターバルベースのスケジューラの複数のインスタンスを使用できます。
// 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式がCronスケジュールによってサポートされていることを検証します。