Cron 中文网
¥Cron for Node.js
🌟 功能
¥🌟 Features
-
每当你的预定作业触发时执行一个函数
¥execute a function whenever your scheduled job triggers
-
使用
child_process
在 javascript 进程之外执行作业(如系统命令)¥execute a job external to the javascript process (like a system command) using
child_process
-
使用 Date 或 Luxon DateTime 对象而不是 cron 语法作为回调的触发器
¥use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
-
使用额外的秒数槽(将其关闭将默认为 0 并匹配 Unix 行为)
¥use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)
🚀 安装
¥🚀 Installation
npm install cron
🔄 从 v2 迁移到 v3
¥🔄 Migrating from v2 to v3
随着 TypeScript 版本 3 的引入以及与 UNIX cron 模式的一致,我们做出了一些更改:
¥With the introduction of TypeScript in version 3 and alignment with UNIX cron patterns, a few changes have been made:
Migrating from v2 to v3
月份和星期几索引更改
¥Month & day-of-week indexing changes
-
月份索引:从
0-11
更改为1-12
。因此你需要将所有数字月份增加 1。¥Month Indexing: Changed from
0-11
to1-12
. So you need to increment all numeric months by 1. -
星期几索引:添加了对星期日的
7
的支持。¥Day-of-Week Indexing: Support added for
7
as Sunday.
CronJob
中的调整
¥Adjustments in CronJob
-
构造函数不再接受对象作为其第一个和唯一参数。改用
CronJob.from(argsObject)
。¥The constructor no longer accepts an object as its first and only params. Use
CronJob.from(argsObject)
instead. -
现在按注册的顺序调用回调。
¥Callbacks are now called in the order they were registered.
-
nextDates(count?: number)
现在始终返回一个数组(如果没有提供参数则为空)。对于单个日期,请改用nextDate()
。¥
nextDates(count?: number)
now always returns an array (empty if no argument is provided). UsenextDate()
instead for a single date.
已删除的方法
¥Removed methods
-
删除
job()
方法以支持new CronJob(...args)
/CronJob.from(argsObject)
¥removed
job()
method in favor ofnew CronJob(...args)
/CronJob.from(argsObject)
-
删除
time()
方法以支持new CronTime()
¥removed
time()
method in favor ofnew CronTime()
🛠 基本用法
¥🛠 Basic Usage
import { CronJob } from 'cron';
const job = new CronJob(
'* * * * * *', // cronTime
function () {
console.log('You will see this message every second');
}, // onTick
null, // onComplete
true, // start
'America/Los_Angeles' // timeZone
);
// job.start() is optional here because of the fourth parameter set to true.
// equivalent job using the "from" static method, providing parameters as an object
const job = CronJob.from({
cronTime: '* * * * * *',
onTick: function () {
console.log('You will see this message every second');
},
start: true,
timeZone: 'America/Los_Angeles'
});
注意:在上面的第一个例子中,
CronJob()
的第四个参数会自动启动作业。如果未提供或设置为 falsy,则必须使用job.start()
明确启动作业。¥Note: In the first example above, the fourth parameter to
CronJob()
starts the job automatically. If not provided or set to falsy, you must explicitly start the job usingjob.start()
.
有关更高级的示例,请查看 示例目录。
¥For more advanced examples, check the examples directory.
Cron 模式
¥Cron Patterns
Cron 模式是这个库的支柱。熟悉语法:
¥Cron patterns are the backbone of this library. Familiarize yourself with the syntax:
- `*` Asterisks: Any value
- `1-3,5` Ranges: Ranges and individual values
- `*/2` Steps: Every two units
详细的模式和解释可在 crontab.org 上找到。链接中的示例有五个字段,1 分钟是最细粒度,但我们的 cron 调度支持具有六个字段的增强格式,允许秒级精度。像 crontab.guru 这样的工具可以帮助构建模式,但请记住考虑秒字段。
¥Detailed patterns and explanations are available at crontab.org. The examples in the link have five fields, and 1 minute as the finest granularity, but our cron scheduling supports an enhanced format with six fields, allowing for second-level precision. Tools like crontab.guru can help in constructing patterns but remember to account for the seconds field.
支持的范围
¥Supported Ranges
以下是此库使用的 UNIX Cron 格式的快速参考,以及添加的第二个字段:
¥Here's a quick reference to the UNIX Cron format this library uses, plus an added second field:
field allowed values
----- --------------
second 0-59
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sunday, or use names)
名称也可用于 'month' 和 '星期几' 字段。使用特定日期或月份的前三个字母(大小写无关紧要)。允许使用名称范围和列表。示例:"星期一、星期三、星期五", "jan-mar".
¥Names can also be used for the 'month' and 'day of week' fields. Use the first three letters of the particular day or month (case does not matter). Ranges and lists of names are allowed.\ Examples: "mon,wed,fri", "jan-mar".
陷阱
¥Gotchas
-
由于计算延迟,JS
Date
和 LuxonDateTime
对象都不能保证毫秒级的精度。此模块不包括标准 cron 语法的毫秒精度,但允许通过 JSDate
或 LuxonDateTime
对象指定执行日期。但是,由于这些计算延迟,指定精确的未来执行时间(例如在当前时间上添加一毫秒)可能并不总是有效。据观察,少于 4-5 毫秒的延迟可能会导致不一致。虽然我们可以将所有日期粒度限制为秒,但我们选择允许更高的精度,但会建议用户注意潜在问题。¥Both JS
Date
and LuxonDateTime
objects don't guarantee millisecond precision due to computation delays. This module excludes millisecond precision for standard cron syntax but allows execution date specification through JSDate
or LuxonDateTime
objects. However, specifying a precise future execution time, such as adding a millisecond to the current time, may not always work due to these computation delays. It's observed that delays less than 4-5 ms might lead to inconsistencies. While we could limit all date granularity to seconds, we've chosen to allow greater precision but advise users of potential issues. -
使用
onTick
的箭头函数将它们绑定到父级的this
上下文。因此,他们将无法访问 cronjob 的this
上下文。你可以在问题 #47(评论) 中阅读更多内容。¥Using arrow functions for
onTick
binds them to the parent'sthis
context. As a result, they won't have access to the cronjob'sthis
context. You can read a little more in issue #47 (comment).
API
独立函数
¥Standalone Functions
-
sendAt
:表示CronTime
将何时执行(返回一个 LuxonDateTime
对象)。¥
sendAt
: Indicates when aCronTime
will execute (returns a LuxonDateTime
object).import * as cron from 'cron';
const dt = cron.sendAt('0 0 * * *');
console.log(`The job would run at: ${dt.toISO()}`); -
timeout
:表示未来CronTime
将执行的毫秒数(返回一个数字)。¥
timeout
: Indicates the number of milliseconds in the future at which aCronTime
will execute (returns a number).import * as cron from 'cron';
const timeout = cron.timeout('0 0 * * *');
console.log(`The job would run in ${timeout}ms`);
CronJob 类
¥CronJob Class
构造函数
¥Constructor
constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)
:
-
cronTime
:[REQUIRED] - 启动工作的时间。可以是 cron 语法、JSDate
对象或 LuxonDateTime
对象。¥
cronTime
: [REQUIRED] - The time to fire off your job. Can be cron syntax, a JSDate
object or a LuxonDateTime
object. -
onTick
:[REQUIRED] - 在指定时间执行的函数。如果提供了onComplete
回调,onTick
将将其作为参数接收。¥
onTick
: [REQUIRED] - Function to execute at the specified time. If anonComplete
callback was provided,onTick
will receive it as an argument. -
onComplete
:[OPTIONAL] - 当作业因job.stop()
而停止时调用。它也可能由onTick
在运行后触发。¥
onComplete
: [OPTIONAL] - Invoked when the job is halted withjob.stop()
. It might also be triggered byonTick
post its run. -
start
:[OPTIONAL] - 确定作业是否应在构造函数退出之前开始。默认为false
。¥
start
: [OPTIONAL] - Determines if the job should commence before constructor exit. Default isfalse
. -
timeZone
:[OPTIONAL] - 设置执行时区。默认为当地时间。检查 Luxon 文档 中的有效格式。¥
timeZone
: [OPTIONAL] - Sets the execution time zone. Default is local time. Check valid formats in the Luxon documentation. -
context
:[OPTIONAL] - onTick 方法的执行上下文。¥
context
: [OPTIONAL] - Execution context for the onTick method. -
runOnInit
:[OPTIONAL] - 初始化后立即触发onTick
函数。默认为false
。¥
runOnInit
: [OPTIONAL] - Instantly triggers theonTick
function post initialization. Default isfalse
. -
utcOffset
:[OPTIONAL] - 以分钟为单位指定时区偏移量。无法与timeZone
共存。¥
utcOffset
: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist withtimeZone
. -
unrefTimeout
:[OPTIONAL] - 用于控制事件循环行为。更多 此处 详细信息。¥
unrefTimeout
: [OPTIONAL] - Useful for controlling event loop behavior. More details here.
方法
¥Methods
-
from
(静态):创建一个新的 CronJob 对象,以对象形式提供参数。请参阅上面的参数名称和说明。¥
from
(static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above. -
start
:启动工作。¥
start
: Initiates the job. -
stop
:停止工作。¥
stop
: Halts the job. -
setTime
:修改CronJob
的时间。参数必须是CronTime
。¥
setTime
: Modifies the time for theCronJob
. Parameter must be aCronTime
. -
lastDate
:提供最后执行日期。¥
lastDate
: Provides the last execution date. -
nextDate
:表示将激活onTick
的后续日期。¥
nextDate
: Indicates the subsequent date that will activate anonTick
. -
nextDates(count)
:提供将启动onTick
的即将到来的日期数组。¥
nextDates(count)
: Supplies an array of upcoming dates that will initiate anonTick
. -
fireOnTick
:允许修改onTick
调用行为。¥
fireOnTick
: Allows modification of theonTick
calling behavior. -
addCallback
:允许添加onTick
回调。¥
addCallback
: Permits addition ofonTick
callbacks.
CronTime 类
¥CronTime Class
构造函数
¥Constructor
constructor(time, zone, utcOffset)
:
-
time
:[REQUIRED] - 启动工作的时间。接受 cron 语法或 JS 日期 对象。¥
time
: [REQUIRED] - The time to initiate your job. Accepts cron syntax or a JS Date object. -
zone
:[OPTIONAL] - 相当于CronJob
参数中的timeZone
。¥
zone
: [OPTIONAL] - Equivalent totimeZone
fromCronJob
parameters. -
utcOffset
:[OPTIONAL] - 类似于CronJob
参数中的utcOffset
。¥
utcOffset
: [OPTIONAL] - Analogous toutcOffset
fromCronJob
parameters.
🤝 社区
¥🤝 Community
加入 Discord 服务器!在这里,你可以在比 GitHub 更随意的论坛中讨论问题并获得帮助。
¥Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.
🌍 贡献
¥🌍 Contributing
这个项目正在寻求帮助!如果你有兴趣帮助该项目,请查看我们的 贡献文档。
¥This project is looking for help! If you're interested in helping with the project, please take a look at our contributing documentation.
🐛 提交错误/问题
¥🐛 Submitting Bugs/Issues
请查看我们的 贡献文档,它包含提交问题前需要了解的所有信息。
¥Please have a look at our contributing documentation, it contains all the information you need to know before submitting an issue.
🙏 致谢
¥🙏 Acknowledgements
这是一个社区努力项目。从真正意义上讲,这个项目始于 cron.js 的一个开源项目,然后发展成为其他项目。其他人为项目贡献了代码、时间和监督。此时,这里要一一列举的太多了,所以我们只能说声谢谢。
¥This is a community effort project. In the truest sense, this project started as an open source project from cron.js and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so we'll just say thanks.
特别感谢 Hiroki Horiuchi、Lundarl Gholoi 和 koooge 在 DefinitelyTyped 类型被导入 v2.4.0 之前所做的工作。
¥Special thanks to Hiroki Horiuchi, Lundarl Gholoi and koooge for their work on the DefinitelyTyped typings before they were imported in v2.4.0.
许可证
¥License
MIT