Parser dan penjadwal cron nol-dependensi untuk Node.js, Deno dan browser. Diterbitkan di NPM dan JSR
Melalui NPM:
$ npm install cron-schedule
Melalui benang:
$ yarn add cron-schedule
Melalui PNPM:
$ pnpm add cron-schedule
Kami menguji kode kami terhadap rilis Node.js berikut ( 18.20
, 20.12
). Versi lain dari Node.js juga dapat berfungsi, tetapi ini tidak diuji.
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 >
Contoh -contoh di atas menggunakan 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
Atau Anda dapat menggunakan deno add @p4sca1/cron-schedule
dan Impor dari @p4sca1/cron-schedule
, atau Impor dari jsr:@p4sca1/cron-schedule
tanpa langkah instalasi.
URL CDN Impor Deno dan Skypack berisi A :version
Placeholder. Ganti :version
dengan versi yang diinginkan. Rentang SEMVER didukung. Untuk selalu menggunakan versi 4.x
terbaru, gunakan ^4.0.0
. Lihat https://www.npmjs.com/package/cron-schedule untuk daftar versi yang tersedia.
// 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
Anda dapat menjadwalkan tugas yang akan dieksekusi berdasarkan ekspresi cron. Jadwal cron hadir dengan 2 penjadwal yang berbeda.
Jika Anda menggunakan TypeScript, pastikan Anda mengatur compilerOptions.moduleResolution
ke node16
atau nodenext
.
Penjadwal Cron berbasis timer membuat satu timer untuk setiap cron yang dijadwalkan. Ketika batas batas waktu simpul ~ 24 hari akan terlampaui, ia menggunakan beberapa batas waktu berturut -turut.
// 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
Pro:
Kontra:
Penjadwal berbasis interval memeriksa tugas karena interval tetap. Jadi hanya ada satu interval untuk semua tugas yang ditugaskan untuk penjadwal. Anda dapat memiliki beberapa contoh penjadwal berbasis interval.
// 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 ( )
Pro:
Kontra:
Bagi kebanyakan orang, penjadwal berbasis timer harus menjadi pilihan yang baik. Namun, SetTimeout bisa tidak dapat diandalkan untuk penundaan lama. Ketika Anda memiliki masalah dengan waktu yang lama / interval dilewati, atau memiliki masalah kinerja karena banyak tugas yang dijadwalkan, Anda harus mempertimbangkan penjadwal berbasis interval.
Cron_schedule menggunakan sintaks Linux Cron seperti yang dijelaskan di sini dengan penambahan yang dapat Anda tentukan secara opsional detik dengan mempersiapkan bidang menit dengan bidang lain.
┌───────────── second (0 - 59, optional)
│ ┌───────────── minute (0 - 59)
│ │ ┌───────────── hour (0 - 23)
│ │ │ ┌───────────── day of month (1 - 31)
│ │ │ │ ┌───────────── month (1 - 12)
│ │ │ │ │ ┌───────────── weekday (0 - 7)
* * * * * *
Semua fitur Linux Cron didukung, termasuk
Untuk tugas waktu sederhana seperti setiap detik x, Anda harus mempertimbangkan untuk menggunakan setInterval
yang lebih cocok untuk tugas waktu sederhana, karena tidak memiliki overhead perhitungan.
Mencari cara untuk memvalidasi ekspresi cron di backend Anda (node.js) atau di browser dengan dukungan untuk beberapa preset? Lihat Cron-Validate!
Gunakan preset npm-cron-schedule
untuk memvalidasi bahwa ekspresi cron didukung oleh jadwal cron .