温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/docs/runtime/cron
点击访问原文链接
Cron - BunDocumentation Index

Fetch the complete documentation index at: /docs/llms.txt

Use this file to discover all available pages before exploring further.

Skip to main contentBun home pageSearch...⌘KInstall BunSearch...NavigationProcess & SystemCronRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicenseOn this pageQuickstartBun.cron.parse()ParametersReturnsChaining callsCron expression syntaxSpecial charactersNamed valuesPredefined nicknamesTime zoneDay-of-month and day-of-week interactionBun.cron(schedule, handler) — in-processParametersNo-overlap guaranteeError handlingbun --hotThe CronJob handleFake timersBun.cron(path, schedule, title) — OS-levelParametersThe scheduled() handlerHow it works per platformLinuxmacOSWindowsUser contextTrigger limitWindows containersBun.cron.remove()Process & SystemCronCopy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">*]:[overflow-wrap:anywhere]">

Schedule and parse cron jobs with Bun

Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">Bun has built-in support for cron — parse expressions, run a callback on a schedule inside your process, or register OS-level jobs that survive restarts. ​Quickstart Run a callback on a schedule in the current process:
Bun.cron("0 * * * *", async () => {
await cleanupTempFiles();
});
Parse a cron expression to find the next matching time:
// Next weekday at 9:30 AM UTC
const next = Bun.cron.parse("30 9 * * MON-FRI");
Register an OS-level cron job that runs a script on a schedule:
await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report");
​Bun.cron.parse() Parse a cron expression and return the next matching Date in UTC.
const next = Bun.cron.parse("*/15 * * * *");
console.log(next); // => next quarter-hour boundary
​Parameters ParameterTypeDescriptionexpressionstringA 5-field cron expression or predefined nicknamerelativeDateDate | numberStarting point for the search (defaults to Date.now()) ​Returns Date | null — the next matching time, or null if no match exists within 8 years (e.g. February 30th). ​Chaining calls Call parse() repeatedly to get a sequence of upcoming times:
let cursor: Date | number = Date.now();
for (let i = 0; i 3; i++) {
cursor = Bun.cron.parse("0 * * * *", cursor)!;
console.log(cursor.toLocaleString()); // next three top-of-hour boundaries
}
​Cron expression syntax Standard 5-field format: minute hour day-of-month month day-of-week FieldValuesSpecial charactersMinute0–59* , - /Hour0–23* , - /Day of month1–31* , - /Month1–12 or JAN–DEC* , - /Day of week0–7 or SUN–SAT* , - / ​Special characters CharacterDescriptionExample*All values* * * * * — every minute,List1,15 * * * * — minute 1 and 15-Range9-17 * * * * — minutes 9 through 17/Step*/15 * * * * — every 15 minutes ​Named values Month and weekday fields accept case-insensitive names:
// 3-letter abbreviations
Bun.cron.parse("0 9 * * MON-FRI"); // weekdays
Bun.cron.parse("0 0 1 JAN,JUN *"); // January and June

// Full names
Bun.cron.parse("0 9 * * Monday-Friday");
Bun.cron.parse("0 0 1 January *");
Both 0 and 7 mean Sunday in the weekday field. ​Predefined nicknames NicknameEquivalentDescription@yearly / @annually0 0 1 1 *Once a year (January 1st)@monthly0 0 1 * *Once a month (1st day)@weekly0 0 * * 0Once a week (Sunday)@daily / @midnight0 0 * * *Once a day (midnight)@hourly0 * * * *Once an hour
const next = Bun.cron.parse("@daily");
console.log(next); // => next UTC midnight
​Time zone Bun.cron.parse() and the in-process Bun.cron(schedule, handler) interpret schedules in UTC. There is no DST to handle — 0 9 * * * always means 9:00 UTC. The OS-level Bun.cron(path, schedule, title) uses the system’s local time zone, because that’s how crontab, launchd, and Windows Task Scheduler work. To make the two forms agree, run the process with TZ=UTC. ​Day-of-month and day-of-week interaction When both day-of-month and day-of-week are specified (neither is *), the expression matches when either condition is true. This follows the POSIX cron standard.
// Fires on the 15th of every month OR every Friday
Bun.cron.parse("0 0 15 * FRI");
When only one is specified (the other is *), only that field is used for matching. ​Bun.cron(schedule, handler) — in-process Run a callback on a cron schedule inside the current process.
const job = Bun.cron("*/5 * * * *", async () => {
await syncToDatabase();
});
This is the lightweight option for long-running servers and workers — no system cron daemon required, works the same on every platform, and shares state (database pools, caches, module-level variables) between invocations. In-processOS-levelSurvives process exit/rebootNoYesShared state between runsYesNo (fresh process each time)Platform requirementsNonecrontab / launchd / Task SchedulerWindows expression limitsNone48-trigger capReturn typeCronJobPromise ​Parameters ParameterTypeDescriptionschedulestringA cron expression or nickname like "@hourly".handler(this: CronJob) => unknownCalled on each fire. May return a Promise — the next fire is not scheduled until it settles. Inside a function callback, this is the CronJob (so this.stop() works). Returns a CronJob synchronously. Throws a TypeError if the expression is invalid or has no future occurrences (e.g. "0 0 30 2 *" — February 30th). ​No-overlap guarantee The next fire time is computed only after the handler — including any returned Promise — settles. If your handler takes 90 seconds and the schedule is * * * * *, the second fire is the first minute boundary after the handler finishes, not 60 seconds after the first fire. Invocations never stack. ​Error handling Errors match setTimeout semantics: A synchronous throw emits process.on("uncaughtException"). A rejected returned Promise emits process.on("unhandledRejection"). Without a listener, the process exits with code 1. With a listener, the job keeps running — it does not stop on the first failure.
process.on("unhandledRejection", err => log.error("cron failed:", err));

Bun.cron("* * * * *", async () => {
await mightThrow(); // logged and retried next minute
});
​bun --hot Under bun --hot, all in-process cron jobs are stopped immediately before the module graph re-evaluates. Every Bun.cron() call still in your source then re-registers. Editing the schedule, editing the handler, or deleting the line entirely all take effect on save without leaking timers. ​The CronJob handle
using job = Bun.cron("0 * * * *", () => {});

job.cron; // => "0 * * * *"
job.stop(); // cancel — the handler will not fire again
job.unref(); // allow the process to exit even while scheduled
job.ref(); // keep the process alive (default)
CronJob is Disposable — using job = Bun.cron(...) auto-stops at scope exit. stop(), ref(), and unref() all return the job for chaining. ​Fake timers In-process cron is anchored to the real wall clock. jest.useFakeTimers(), setSystemTime(), advanceTimersByTime(), and runAllTimers() do not affect when it fires. ​Bun.cron(path, schedule, title) — OS-level Register an OS-level cron job that runs a JavaScript/TypeScript module on a schedule.
await Bun.cron("./worker.ts", "30 2 * * MON", "weekly-report");
​Parameters ParameterTypeDescriptionpathstringPath to the script (resolved relative to caller)schedulestringCron expression or nicknametitlestringUnique job identifier (alphanumeric, hyphens, underscores) Re-registering with the same title overwrites the existing job in-place — the old schedule is replaced, not duplicated.
await Bun.cron("./worker.ts", "0 * * * *", "my-job"); // every hour
await Bun.cron("./worker.ts", "*/15 * * * *", "my-job"); // replaces: every 15 min
​The scheduled() handler The registered script must export a default object with a scheduled() method, following the Cloudflare Workers Cron Triggers API: worker.ts
export default {
scheduled(controller: Bun.CronController) {
console.log(controller.cron); // "30 2 * * 1"
console.log(controller.type); // "scheduled"
console.log(controller.scheduledTime); // 1737340201847 (Date.now() at invocation)
},
};
The handler can be async. Bun waits for the returned promise to settle before exiting. ​How it works per platform ​Linux Bun uses crontab to register jobs. Each job is stored as a line in your user’s crontab with a # bun-cron: marker comment above it. The crontab entry looks like:
 '' run --cron-title= --cron-period='' '                    

Cron - Bun,AI智能索引,全网链接索引,智能导航,网页索引

    Schedule and parse cron jobs with Bun