fix(cronmanager): improve cron scheduling and lifecycle handling; add wake/wakeCycle to promptly recalculate scheduling when jobs are added/removed/started/stopped, fix timeout handling, and update tests and deps
This commit is contained in:
11
changelog.md
11
changelog.md
@@ -1,5 +1,16 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2026-02-15 - 4.2.1 - fix(cronmanager)
|
||||||
|
improve cron scheduling and lifecycle handling; add wake/wakeCycle to promptly recalculate scheduling when jobs are added/removed/started/stopped, fix timeout handling, and update tests and deps
|
||||||
|
|
||||||
|
- CronManager: add wakeCycle (Deferred) to wake the sleeping cycle immediately when jobs change
|
||||||
|
- CronManager: refactor runCronCycle to compute the soonest next execution (soonestMs), await timeout or wake signal, handle overdue jobs without waiting, and cancel timeouts to avoid lingering timers
|
||||||
|
- CronJob: guard checkExecution to return when job status is 'stopped' to prevent unnecessary scheduling work
|
||||||
|
- Stop logic: safely cancel executionTimeout only if present and ensure the cycle is woken when stopping
|
||||||
|
- Tests: switch test imports to @git.zone/tstest/tapbundle
|
||||||
|
- Dependencies: bump several devDependencies and dependencies (tsbuild, tsbundle, tstest, croner, smartpromise, dayjs, pretty-ms, etc.)
|
||||||
|
- Docs/config: expand README with examples and security/reporting info; add @git.zone/cli release config to npmextra.json
|
||||||
|
|
||||||
## 2024-12-14 - 4.2.0 - feat(ondemand)
|
## 2024-12-14 - 4.2.0 - feat(ondemand)
|
||||||
Add on-demand timestamp feature
|
Add on-demand timestamp feature
|
||||||
|
|
||||||
|
|||||||
@@ -25,5 +25,13 @@
|
|||||||
},
|
},
|
||||||
"tsdoc": {
|
"tsdoc": {
|
||||||
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
|
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
|
||||||
|
},
|
||||||
|
"@git.zone/cli": {
|
||||||
|
"release": {
|
||||||
|
"registries": [
|
||||||
|
"https://registry.npmjs.org"
|
||||||
|
],
|
||||||
|
"accessLevel": "public"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
22
package.json
22
package.json
@@ -13,22 +13,22 @@
|
|||||||
"buildDocs": "tsdoc"
|
"buildDocs": "tsdoc"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@git.zone/tsbuild": "^2.2.0",
|
"@git.zone/tsbuild": "^4.1.2",
|
||||||
"@git.zone/tsbundle": "^2.1.0",
|
"@git.zone/tsbundle": "^2.8.3",
|
||||||
"@git.zone/tsrun": "^1.3.3",
|
"@git.zone/tsrun": "^2.0.1",
|
||||||
"@git.zone/tstest": "^1.0.90",
|
"@git.zone/tstest": "^3.1.8",
|
||||||
"@push.rocks/tapbundle": "^5.5.3",
|
"@push.rocks/tapbundle": "^6.0.3",
|
||||||
"@types/node": "^22.10.2"
|
"@types/node": "^25.2.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@push.rocks/lik": "^6.1.0",
|
"@push.rocks/lik": "^6.2.2",
|
||||||
"@push.rocks/smartdelay": "^3.0.5",
|
"@push.rocks/smartdelay": "^3.0.5",
|
||||||
"@push.rocks/smartpromise": "^4.0.4",
|
"@push.rocks/smartpromise": "^4.2.3",
|
||||||
"croner": "^9.0.0",
|
"croner": "^10.0.1",
|
||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"dayjs": "^1.11.13",
|
"dayjs": "^1.11.19",
|
||||||
"is-nan": "^1.3.2",
|
"is-nan": "^1.3.2",
|
||||||
"pretty-ms": "^9.2.0"
|
"pretty-ms": "^9.3.0"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"ts/**/*",
|
"ts/**/*",
|
||||||
|
|||||||
9130
pnpm-lock.yaml
generated
9130
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
268
readme.md
268
readme.md
@@ -1,147 +1,283 @@
|
|||||||
# @push.rocks/smarttime
|
# @push.rocks/smarttime
|
||||||
handle time in smart ways
|
|
||||||
|
Handle time in smart ways — cron scheduling, extended dates, precise measurements, timers, intervals, and human-readable formatting. 🕐
|
||||||
|
|
||||||
|
## Issue Reporting and Security
|
||||||
|
|
||||||
|
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
To install `@push.rocks/smarttime`, use the following npm command:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install @push.rocks/smarttime --save
|
npm install @push.rocks/smarttime
|
||||||
```
|
```
|
||||||
|
|
||||||
This will add `@push.rocks/smarttime` to your project's dependencies.
|
or with pnpm:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install @push.rocks/smarttime
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
`@push.rocks/smarttime` provides a comprehensive toolkit for handling various aspects of time manipulation, scheduling, and comparison in a TypeScript project. The following sections will guide you through the capabilities of this package, showcasing how to use its classes and functions effectively.
|
`@push.rocks/smarttime` is a comprehensive TypeScript-first toolkit for working with time. It covers everything from cron-based scheduling and extended date manipulation to high-resolution measurements, timers, intervals, and human-readable time formatting.
|
||||||
|
|
||||||
### Handling Time Units and Calculations
|
All examples below use ESM imports and TypeScript.
|
||||||
|
|
||||||
|
### ⏱️ Time Units & Calculations
|
||||||
|
|
||||||
|
Convert human-readable time durations into milliseconds using the `units` helpers and `getMilliSecondsFromUnits`:
|
||||||
|
|
||||||
#### Working with Units
|
|
||||||
```typescript
|
```typescript
|
||||||
import { units, getMilliSecondsFromUnits } from '@push.rocks/smarttime';
|
import { units, getMilliSecondsFromUnits } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
// Define a duration using a combination of time units
|
// Individual unit conversions
|
||||||
let durationInMilliseconds = getMilliSecondsFromUnits({
|
const oneDay = units.days(1); // 86400000
|
||||||
|
const twoHours = units.hours(2); // 7200000
|
||||||
|
const thirtySeconds = units.seconds(30); // 30000
|
||||||
|
|
||||||
|
// Combined duration — great for timeouts, TTLs, cache expiration, etc.
|
||||||
|
const duration = getMilliSecondsFromUnits({
|
||||||
years: 1,
|
years: 1,
|
||||||
months: 2,
|
months: 2,
|
||||||
weeks: 3,
|
weeks: 3,
|
||||||
days: 4,
|
days: 4,
|
||||||
hours: 5,
|
hours: 5,
|
||||||
minutes: 6,
|
minutes: 6,
|
||||||
seconds: 7
|
seconds: 7,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`Duration in milliseconds: ${durationInMilliseconds}`);
|
console.log(`Duration: ${duration}ms`);
|
||||||
```
|
```
|
||||||
|
|
||||||
In the example above, we specify a complex duration made up of various time units using the `getMilliSecondsFromUnits` function. This is quite useful for calculations where you need to define durations in a more human-readable format.
|
### 🗓️ Human-Readable Time Formatting
|
||||||
|
|
||||||
### Scheduling with CronManager
|
Turn raw milliseconds into a friendly string, or get a relative "time ago" description:
|
||||||
|
|
||||||
`@push.rocks/smarttime` includes a powerful scheduling tool called `CronManager`, which allows you to schedule tasks using cron syntax.
|
```typescript
|
||||||
|
import {
|
||||||
|
getMilliSecondsAsHumanReadableString,
|
||||||
|
getMilliSecondsAsHumanReadableAgoTime,
|
||||||
|
} from '@push.rocks/smarttime';
|
||||||
|
|
||||||
|
// "2h 30m"
|
||||||
|
console.log(getMilliSecondsAsHumanReadableString(9_000_000));
|
||||||
|
|
||||||
|
// "5 minutes ago" style output
|
||||||
|
const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
|
||||||
|
console.log(getMilliSecondsAsHumanReadableAgoTime(fiveMinutesAgo));
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🔄 CronManager — Scheduled Task Execution
|
||||||
|
|
||||||
|
The `CronManager` lets you register and run multiple cron jobs using standard 6-field cron syntax (seconds included). Powered by [croner](https://github.com/Hexagon/croner).
|
||||||
|
|
||||||
#### Creating and Starting a CronManager
|
|
||||||
```typescript
|
```typescript
|
||||||
import { CronManager } from '@push.rocks/smarttime';
|
import { CronManager } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
const cronManager = new CronManager();
|
const cronManager = new CronManager();
|
||||||
|
|
||||||
// Adding a cron job that runs every minute
|
// Run every 10 seconds
|
||||||
cronManager.addCronjob('* * * * *', async () => {
|
const job1 = cronManager.addCronjob('*/10 * * * * *', async (triggerTime) => {
|
||||||
console.log('This task runs every minute.');
|
console.log(`Job 1 triggered at ${new Date(triggerTime).toISOString()}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Starting the CronManager
|
// Run every full minute
|
||||||
|
const job2 = cronManager.addCronjob('0 * * * * *', async () => {
|
||||||
|
console.log('Full minute tick!');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start all registered jobs
|
||||||
cronManager.start();
|
cronManager.start();
|
||||||
|
|
||||||
|
// Later: remove a specific job
|
||||||
|
cronManager.removeCronjob(job1);
|
||||||
|
|
||||||
|
// Stop all jobs
|
||||||
|
cronManager.stop();
|
||||||
```
|
```
|
||||||
|
|
||||||
The example demonstrates how to create a `CronManager`, add a cron job that runs every minute, and start the scheduling. You can add multiple cron jobs to a single manager, each with its own scheduling and task.
|
The `CronManager` automatically calculates the shortest sleep interval between jobs and efficiently schedules wake-ups — no polling required.
|
||||||
|
|
||||||
### Working with Extended Date Class
|
### 📅 ExtendedDate — Enhanced Date Handling
|
||||||
|
|
||||||
The `ExtendedDate` class extends the native JavaScript `Date` object, providing additional functionality for handling dates in various formats and zones.
|
`ExtendedDate` extends the native JavaScript `Date` with factory methods for common date formats and useful inspection methods:
|
||||||
|
|
||||||
#### Creating ExtendedDate Instances
|
|
||||||
```typescript
|
```typescript
|
||||||
import { ExtendedDate } from '@push.rocks/smarttime';
|
import { ExtendedDate } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
// Creating a date from a European format string
|
// From European format: "DD.MM.YYYY"
|
||||||
const dateFromEuroString = ExtendedDate.fromEuropeanDate('31.12.2023');
|
const date1 = ExtendedDate.fromEuropeanDate('25.12.2024');
|
||||||
console.log(dateFromEuroString.toString());
|
|
||||||
|
|
||||||
// Creating a date from a hyphed date string
|
// From European date + time with timezone context
|
||||||
const dateFromHyphedString = ExtendedDate.fromHyphedDate('2023-12-31');
|
const date2 = ExtendedDate.fromEuropeanDateAndTime('25.12.2024', '14:30:00', 'Europe/Berlin');
|
||||||
console.log(dateFromHyphedString.toString());
|
|
||||||
|
// From hyphenated date: "YYYY-MM-DD"
|
||||||
|
const date3 = ExtendedDate.fromHyphedDate('2024-12-25');
|
||||||
|
|
||||||
|
// From milliseconds
|
||||||
|
const date4 = ExtendedDate.fromMillis(Date.now());
|
||||||
|
|
||||||
|
// From an existing Date object
|
||||||
|
const date5 = ExtendedDate.fromDate(new Date());
|
||||||
|
|
||||||
|
// Export back to various formats
|
||||||
|
console.log(date1.exportToEuropeanDate()); // "25.12.2024"
|
||||||
|
console.log(date1.exportToHyphedSortableDate()); // "2024-12-25"
|
||||||
|
|
||||||
|
// Get structured date units
|
||||||
|
const units = date1.exportToUnits();
|
||||||
|
console.log(units.monthName); // "December"
|
||||||
|
console.log(units.dayOfTheWeekName); // "Wednesday"
|
||||||
|
|
||||||
|
// Custom formatting (via dayjs)
|
||||||
|
console.log(date1.format('YYYY-MM-DD HH:mm'));
|
||||||
|
|
||||||
|
// Boolean checks
|
||||||
|
console.log(date4.isToday()); // true
|
||||||
|
|
||||||
|
// Time comparison: has less than 1 hour passed since this date?
|
||||||
|
console.log(date4.lessTimePassedToNow({ hours: 1 })); // true
|
||||||
|
console.log(date4.moreTimePassedToNow({ days: 1 })); // false
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Checking if a Date is Today
|
### ⏱️ HrtMeasurement — High-Resolution Timing
|
||||||
```typescript
|
|
||||||
import { ExtendedDate } from '@push.rocks/smarttime';
|
|
||||||
|
|
||||||
const someDate = new ExtendedDate();
|
Measure the duration of operations with precision:
|
||||||
console.log(`Is someDate today? ${someDate.isToday()}`);
|
|
||||||
```
|
|
||||||
|
|
||||||
Using `ExtendedDate`, you can also easily check if a given date is today. This simplifies certain date comparisons that are common in web and application development.
|
|
||||||
|
|
||||||
### High-Resolution Time Measurement
|
|
||||||
For performance testing and high-resolution time tracking, `@push.rocks/smarttime` provides the `HrtMeasurement` class.
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { HrtMeasurement } from '@push.rocks/smarttime';
|
import { HrtMeasurement } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
const hrtMeasurement = new HrtMeasurement();
|
const measurement = new HrtMeasurement();
|
||||||
hrtMeasurement.start();
|
measurement.start();
|
||||||
// Simulate some operations...
|
|
||||||
setTimeout(() => {
|
// ... perform some operation ...
|
||||||
hrtMeasurement.stop();
|
|
||||||
console.log(`Operation took ${hrtMeasurement.milliSeconds} milliseconds.`);
|
measurement.stop();
|
||||||
}, 1000);
|
console.log(`Took ${measurement.milliSeconds}ms`);
|
||||||
|
console.log(`Took ${measurement.nanoSeconds}ns`);
|
||||||
|
|
||||||
|
// Reset and reuse
|
||||||
|
measurement.reset();
|
||||||
|
measurement.start();
|
||||||
|
// ...
|
||||||
```
|
```
|
||||||
|
|
||||||
This class allows you to measure the duration of operations in your code with high precision, offering both milliseconds and nanoseconds resolutions.
|
### ⏲️ Timer — Pausable Countdown
|
||||||
|
|
||||||
### Interval and Timer functionalities
|
A promise-based timer with pause, resume, and reset capabilities:
|
||||||
|
|
||||||
`@push.rocks/smarttime` includes classes for managing intervals and timers with enhanced control, such as pause, resume, and reset capabilities.
|
|
||||||
|
|
||||||
#### Using the Timer class
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Timer } from '@push.rocks/smarttime';
|
import { Timer } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
const timer = new Timer(5000); // A 5-second timer
|
const timer = new Timer(5000); // 5-second countdown
|
||||||
timer.start();
|
timer.start();
|
||||||
|
|
||||||
timer.completed.then(() => {
|
// Await completion
|
||||||
console.log('Timer completed!');
|
await timer.completed;
|
||||||
});
|
console.log('Timer finished!');
|
||||||
|
|
||||||
// Resetting the timer
|
// Or use pause/resume
|
||||||
timer.reset();
|
const timer2 = new Timer(10000);
|
||||||
timer.start();
|
timer2.start();
|
||||||
|
|
||||||
|
// Pause after 3 seconds
|
||||||
|
setTimeout(() => timer2.pause(), 3000);
|
||||||
|
|
||||||
|
// Resume later
|
||||||
|
setTimeout(() => timer2.resume(), 6000);
|
||||||
|
|
||||||
|
await timer2.completed;
|
||||||
|
|
||||||
|
// Reset completely and start over
|
||||||
|
timer2.reset();
|
||||||
|
timer2.start();
|
||||||
```
|
```
|
||||||
|
|
||||||
The `Timer` class allows for asynchronous waiting in a more object-oriented manner. In the example, a `Timer` is created for five seconds, started, and then reset for demonstration purposes.
|
Check remaining time with `timer.timeLeft`.
|
||||||
|
|
||||||
### Conclusion
|
### 🔁 Interval — Repeating Jobs
|
||||||
|
|
||||||
`@push.rocks/smarttime` offers an extensive toolkit for dealing with time in JavaScript and TypeScript applications. Whether you need precise timing, scheduled tasks, or extended date functionalities, this package provides a suite of tools designed to handle time in smart and efficient ways. The examples provided herein demonstrate the core functionalities, aiming to help you integrate time-related features into your projects with ease.
|
Run functions at a fixed interval with start/stop control:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Interval } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
|
const interval = new Interval(2000); // Every 2 seconds
|
||||||
|
|
||||||
|
interval.addIntervalJob(() => {
|
||||||
|
console.log('Tick!', new Date().toISOString());
|
||||||
|
});
|
||||||
|
|
||||||
|
interval.addIntervalJob(() => {
|
||||||
|
console.log('Another parallel job');
|
||||||
|
});
|
||||||
|
|
||||||
|
interval.start();
|
||||||
|
|
||||||
|
// Stop later
|
||||||
|
setTimeout(() => interval.stop(), 10000);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🕰️ TimeStamp — Comparison & Tracking
|
||||||
|
|
||||||
|
The `TimeStamp` class captures a moment in time and provides comparison utilities:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { TimeStamp } from '@push.rocks/smarttime';
|
||||||
|
|
||||||
|
const stamp1 = new TimeStamp();
|
||||||
|
// ... some time passes ...
|
||||||
|
const stamp2 = new TimeStamp();
|
||||||
|
|
||||||
|
console.log(stamp1.milliSeconds); // Unix ms
|
||||||
|
console.log(stamp1.epochtime); // Unix seconds
|
||||||
|
|
||||||
|
// Comparison
|
||||||
|
console.log(stamp1.isOlderThan(stamp2)); // true
|
||||||
|
console.log(stamp2.isYoungerThanOtherTimeStamp(stamp1)); // true
|
||||||
|
|
||||||
|
// Derived timestamps track change
|
||||||
|
const derived = TimeStamp.fromTimeStamp(stamp1);
|
||||||
|
console.log(`${derived.change}ms have passed since stamp1`);
|
||||||
|
|
||||||
|
// From known milliseconds
|
||||||
|
const known = TimeStamp.fromMilliSeconds(1700000000000);
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Overview
|
||||||
|
|
||||||
|
| Export | Description |
|
||||||
|
|---|---|
|
||||||
|
| `CronManager` | Register and run multiple cron jobs with automatic scheduling |
|
||||||
|
| `CronJob` | Individual cron job (created via `CronManager.addCronjob()`) |
|
||||||
|
| `ExtendedDate` | Enhanced `Date` with factory methods and formatting |
|
||||||
|
| `HrtMeasurement` | High-resolution time measurement |
|
||||||
|
| `Timer` | Promise-based countdown with pause/resume/reset |
|
||||||
|
| `Interval` | Repeating job execution at fixed intervals |
|
||||||
|
| `TimeStamp` | Point-in-time capture with comparison utilities |
|
||||||
|
| `units` | Time unit conversion functions (`days()`, `hours()`, etc.) |
|
||||||
|
| `getMilliSecondsFromUnits()` | Convert combined time units to milliseconds |
|
||||||
|
| `getMilliSecondsAsHumanReadableString()` | Format ms as human-readable string |
|
||||||
|
| `getMilliSecondsAsHumanReadableAgoTime()` | Format timestamp as relative "ago" string |
|
||||||
|
|
||||||
## License and Legal Information
|
## License and Legal Information
|
||||||
|
|
||||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
||||||
|
|
||||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
### Trademarks
|
### Trademarks
|
||||||
|
|
||||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||||
|
|
||||||
|
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||||
|
|
||||||
### Company Information
|
### Company Information
|
||||||
|
|
||||||
Task Venture Capital GmbH
|
Task Venture Capital GmbH
|
||||||
Registered at District court Bremen HRB 35230 HB, Germany
|
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||||
|
|
||||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||||
|
|
||||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
// tslint:disable-next-line:no-implicit-dependencies
|
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||||
import { expect, tap } from '@push.rocks/tapbundle';
|
|
||||||
import * as smarttime from '../ts/index.js';
|
import * as smarttime from '../ts/index.js';
|
||||||
|
|
||||||
// Test TimeStamp class
|
// Test TimeStamp class
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { tap, expect } from '@push.rocks/tapbundle';
|
import { tap, expect } from '@git.zone/tstest/tapbundle';
|
||||||
|
|
||||||
import * as smarttime from '../ts/index.js';
|
import * as smarttime from '../ts/index.js';
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { expect, tap } from '@push.rocks/tapbundle';
|
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||||
|
|
||||||
import * as smarttime from '../ts/index.js';
|
import * as smarttime from '../ts/index.js';
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
// tslint:disable-next-line:no-implicit-dependencies
|
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||||
import { expect, tap } from '@push.rocks/tapbundle';
|
|
||||||
|
|
||||||
import { Timer } from '../ts/index.js';
|
import { Timer } from '../ts/index.js';
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smarttime',
|
name: '@push.rocks/smarttime',
|
||||||
version: '4.2.0',
|
version: '4.2.1',
|
||||||
description: 'Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.'
|
description: 'Provides utilities for advanced time handling including cron jobs, timestamps, intervals, and more.'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import * as plugins from './smarttime.plugins.js';
|
import * as plugins from './smarttime.plugins.js';
|
||||||
import { CronManager } from './smarttime.classes.cronmanager.js';
|
import { CronManager } from './smarttime.classes.cronmanager.js';
|
||||||
|
|
||||||
import { CronParser } from './smarttime.classes.cronparser.js';
|
|
||||||
|
|
||||||
export type TJobFunction =
|
export type TJobFunction =
|
||||||
| ((triggerTimeArg?: number) => void)
|
| ((triggerTimeArg?: number) => void)
|
||||||
| ((triggerTimeArg?: number) => Promise<any>);
|
| ((triggerTimeArg?: number) => Promise<any>);
|
||||||
@@ -24,6 +22,9 @@ export class CronJob {
|
|||||||
* checks wether the cronjob needs to be executed
|
* checks wether the cronjob needs to be executed
|
||||||
*/
|
*/
|
||||||
public checkExecution(): number {
|
public checkExecution(): number {
|
||||||
|
if (this.status === 'stopped') {
|
||||||
|
return this.nextExecutionUnix;
|
||||||
|
}
|
||||||
if (this.nextExecutionUnix === 0) {
|
if (this.nextExecutionUnix === 0) {
|
||||||
this.getNextExecutionTime();
|
this.getNextExecutionTime();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import * as plugins from './smarttime.plugins.js';
|
import * as plugins from './smarttime.plugins.js';
|
||||||
import { CronJob, type TJobFunction } from './smarttime.classes.cronjob.js';
|
import { CronJob, type TJobFunction } from './smarttime.classes.cronjob.js';
|
||||||
import { getMilliSecondsAsHumanReadableString } from './smarttime.units.js';
|
|
||||||
|
|
||||||
export class CronManager {
|
export class CronManager {
|
||||||
public executionTimeout: plugins.smartdelay.Timeout<void>;
|
public executionTimeout: plugins.smartdelay.Timeout<void>;
|
||||||
@@ -8,13 +7,26 @@ export class CronManager {
|
|||||||
public status: 'started' | 'stopped' = 'stopped';
|
public status: 'started' | 'stopped' = 'stopped';
|
||||||
public cronjobs = new plugins.lik.ObjectMap<CronJob>();
|
public cronjobs = new plugins.lik.ObjectMap<CronJob>();
|
||||||
|
|
||||||
|
private cycleWakeDeferred: plugins.smartpromise.Deferred<void> | null = null;
|
||||||
|
|
||||||
constructor() {}
|
constructor() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves the current wake deferred, causing the sleeping cycle
|
||||||
|
* to immediately recalculate instead of waiting for its timeout.
|
||||||
|
*/
|
||||||
|
private wakeCycle() {
|
||||||
|
if (this.cycleWakeDeferred && this.cycleWakeDeferred.status === 'pending') {
|
||||||
|
this.cycleWakeDeferred.resolve();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public addCronjob(cronIdentifierArg: string, cronFunctionArg: TJobFunction) {
|
public addCronjob(cronIdentifierArg: string, cronFunctionArg: TJobFunction) {
|
||||||
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
|
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
|
||||||
this.cronjobs.add(newCronJob);
|
this.cronjobs.add(newCronJob);
|
||||||
if (this.status === 'started') {
|
if (this.status === 'started') {
|
||||||
newCronJob.start();
|
newCronJob.start();
|
||||||
|
this.wakeCycle();
|
||||||
}
|
}
|
||||||
|
|
||||||
return newCronJob;
|
return newCronJob;
|
||||||
@@ -23,6 +35,9 @@ export class CronManager {
|
|||||||
public removeCronjob(cronjobArg: CronJob) {
|
public removeCronjob(cronjobArg: CronJob) {
|
||||||
cronjobArg.stop();
|
cronjobArg.stop();
|
||||||
this.cronjobs.remove(cronjobArg);
|
this.cronjobs.remove(cronjobArg);
|
||||||
|
if (this.status === 'started') {
|
||||||
|
this.wakeCycle();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,35 +54,39 @@ export class CronManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async runCronCycle() {
|
private async runCronCycle() {
|
||||||
this.executionTimeout = new plugins.smartdelay.Timeout(0);
|
while (this.status === 'started') {
|
||||||
do {
|
// Create a fresh wake signal for this iteration
|
||||||
let nextRunningCronjob: CronJob;
|
this.cycleWakeDeferred = new plugins.smartpromise.Deferred<void>();
|
||||||
|
|
||||||
|
// Check all cronjobs and find the soonest next execution
|
||||||
|
let soonestMs = Infinity;
|
||||||
for (const cronJob of this.cronjobs.getArray()) {
|
for (const cronJob of this.cronjobs.getArray()) {
|
||||||
cronJob.checkExecution();
|
cronJob.checkExecution();
|
||||||
if (
|
const msToNext = cronJob.getTimeToNextExecution();
|
||||||
!nextRunningCronjob ||
|
if (msToNext < soonestMs) {
|
||||||
cronJob.getTimeToNextExecution() < nextRunningCronjob.getTimeToNextExecution()
|
soonestMs = msToNext;
|
||||||
) {
|
|
||||||
nextRunningCronjob = cronJob;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (nextRunningCronjob) {
|
|
||||||
this.executionTimeout = new plugins.smartdelay.Timeout(
|
|
||||||
nextRunningCronjob.getTimeToNextExecution()
|
|
||||||
);
|
|
||||||
console.log(
|
|
||||||
`Next CronJob scheduled in ${getMilliSecondsAsHumanReadableString(
|
|
||||||
this.executionTimeout.getTimeLeft()
|
|
||||||
)}`
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
this.executionTimeout = new plugins.smartdelay.Timeout(1000);
|
|
||||||
console.log('no cronjobs specified! Checking again in 1 second');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.executionTimeout.promise;
|
// Sleep until the next job is due or until woken by a lifecycle event
|
||||||
} while (this.status === 'started');
|
if (soonestMs < Infinity && soonestMs > 0) {
|
||||||
};
|
this.executionTimeout = new plugins.smartdelay.Timeout(soonestMs);
|
||||||
|
await Promise.race([
|
||||||
|
this.executionTimeout.promise,
|
||||||
|
this.cycleWakeDeferred.promise,
|
||||||
|
]);
|
||||||
|
// Cancel the timeout to avoid lingering timers
|
||||||
|
this.executionTimeout.cancel();
|
||||||
|
} else if (soonestMs <= 0) {
|
||||||
|
// Job is overdue, loop immediately to execute it
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
// No jobs — wait indefinitely until woken by addCronjob or stop
|
||||||
|
await this.cycleWakeDeferred.promise;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.cycleWakeDeferred = null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* stops all cronjobs
|
* stops all cronjobs
|
||||||
@@ -75,9 +94,10 @@ export class CronManager {
|
|||||||
public stop() {
|
public stop() {
|
||||||
if (this.status === 'started') {
|
if (this.status === 'started') {
|
||||||
this.status = 'stopped';
|
this.status = 'stopped';
|
||||||
|
if (this.executionTimeout) {
|
||||||
this.executionTimeout.cancel();
|
this.executionTimeout.cancel();
|
||||||
} else {
|
}
|
||||||
console.log(`You tried to stop a CronManager that was not actually started.`);
|
this.wakeCycle();
|
||||||
}
|
}
|
||||||
for (const cron of this.cronjobs.getArray()) {
|
for (const cron of this.cronjobs.getArray()) {
|
||||||
cron.stop();
|
cron.stop();
|
||||||
|
|||||||
Reference in New Issue
Block a user