Compare commits

...

68 Commits

Author SHA1 Message Date
c290a75f01 4.0.2 2023-07-12 11:28:52 +02:00
9a20f8f6a1 fix(core): update 2023-07-12 11:28:52 +02:00
f91fa33568 4.0.1 2023-01-06 20:05:03 +01:00
c234cb4caa fix(core): update 2023-01-06 20:05:02 +01:00
5f5957b0c0 4.0.0 2022-11-21 12:33:26 +01:00
31275536ec BREAKING CHANGE(core): switch to esm 2022-11-21 12:33:25 +01:00
c759d436dd 3.0.48 2022-11-21 11:31:30 +01:00
010c9e7bed fix(core): update 2022-11-21 11:31:29 +01:00
264c08d848 3.0.47 2022-11-21 09:14:32 +01:00
b2a5cda468 fix(core): update 2022-11-21 09:14:32 +01:00
d3dd03534a 3.0.46 2022-11-21 01:19:39 +01:00
9b96779d19 fix(core): update 2022-11-21 01:19:38 +01:00
20b181b2f3 3.0.45 2022-02-02 17:03:59 +01:00
d278722da2 fix(core): update 2022-02-02 17:03:58 +01:00
e3daf08d67 3.0.44 2022-02-02 16:55:13 +01:00
0483b55a9e fix(core): update 2022-02-02 16:55:12 +01:00
c3a772c155 3.0.43 2021-11-08 16:56:11 +01:00
a2ffdd436f fix(timestamp): add missing .isOlderThanOtherTimeStamp() to TimeStamp class 2021-11-08 16:56:11 +01:00
da9c71eedb 3.0.42 2021-11-08 16:52:14 +01:00
63405fc577 fix(readme): fix readme 2021-11-08 16:52:13 +01:00
d789eec558 3.0.41 2021-11-08 16:49:33 +01:00
22027d2308 fix(update croner): update croner package, closes #1. Thank you @Hexagon4 2021-11-08 16:49:33 +01:00
87d29fbb50 3.0.40 2021-11-08 16:40:19 +01:00
1c5a1c21da fix(core): update 2021-11-08 16:40:19 +01:00
969088ad04 3.0.39 2021-10-06 11:58:36 +02:00
76768a1307 fix(core): update 2021-10-06 11:58:36 +02:00
419fe80bde 3.0.38 2021-01-02 19:30:16 +00:00
5a9584917c fix(core): update 2021-01-02 19:30:15 +00:00
2b21ee9a24 3.0.37 2020-10-05 22:28:40 +00:00
3a110c9fd9 fix(core): update 2020-10-05 22:28:40 +00:00
25f7ad37ae 3.0.36 2020-10-05 17:48:42 +00:00
992d167a34 fix(core): update 2020-10-05 17:48:41 +00:00
cfcfde2132 3.0.35 2020-09-07 23:44:08 +00:00
b5ab945501 fix(core): update 2020-09-07 23:44:07 +00:00
88378e2f31 3.0.34 2020-09-07 17:16:12 +00:00
db92311daa fix(core): update 2020-09-07 17:16:11 +00:00
36bff0a70a 3.0.33 2020-09-07 16:44:55 +00:00
fa8fd9fa35 fix(core): update 2020-09-07 16:44:54 +00:00
dd783b455f 3.0.32 2020-09-07 12:13:28 +00:00
996685e7fb fix(core): update 2020-09-07 12:13:27 +00:00
110b2c00cf 3.0.31 2020-09-04 15:18:41 +00:00
c8b455b8e2 fix(core): update 2020-09-04 15:18:41 +00:00
d16fd8b69b 3.0.30 2020-09-04 14:24:42 +00:00
f7ed88cd57 fix(core): update 2020-09-04 14:24:42 +00:00
19b5ba4a5d 3.0.29 2020-09-04 06:39:22 +00:00
457182a97a fix(core): update 2020-09-04 06:39:22 +00:00
a7a961c869 3.0.28 2020-09-03 20:14:23 +00:00
f1d7771e30 fix(core): update 2020-09-03 20:14:23 +00:00
ff16b70206 3.0.27 2020-09-03 20:06:03 +00:00
8e43ce7e9b fix(core): update 2020-09-03 20:06:02 +00:00
f129ce42b6 3.0.26 2020-09-02 14:27:11 +00:00
56a802664f fix(core): update 2020-09-02 14:27:11 +00:00
743c9fb847 3.0.25 2020-09-02 14:09:22 +00:00
ac2edd6d74 fix(core): update 2020-09-02 14:09:21 +00:00
725102d02c 3.0.24 2020-07-12 00:25:56 +00:00
7c73579c9f fix(core): update 2020-07-12 00:25:55 +00:00
a1996ea1bd 3.0.23 2020-07-12 00:00:50 +00:00
dc92ae7140 fix(core): update 2020-07-12 00:00:50 +00:00
3e862f233c 3.0.22 2020-07-11 23:36:24 +00:00
73f7360f8c fix(core): update 2020-07-11 23:36:24 +00:00
2c74de8aef 3.0.21 2020-07-11 23:31:10 +00:00
78498626ea fix(core): update 2020-07-11 23:31:09 +00:00
b2299b149a 3.0.20 2020-07-11 21:41:33 +00:00
885b2432a8 fix(core): update 2020-07-11 21:41:33 +00:00
7a231b7686 3.0.19 2020-07-07 22:37:42 +00:00
ef6e21080e fix(core): update 2020-07-07 22:37:41 +00:00
3ea8b1564d 3.0.18 2020-05-27 18:16:12 +00:00
1b92240c4e fix(core): update 2020-05-27 18:16:11 +00:00
27 changed files with 5391 additions and 3503 deletions

View File

@ -12,30 +12,38 @@ stages:
- release
- metadata
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- lossless
- docker
- notpriv
audit:
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
tags:
- lossless
- docker
- notpriv
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --dev
tags:
- lossless
- docker
allow_failure: true
# ====================
# test stage
@ -44,28 +52,22 @@ audit:
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- priv
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker
- notpriv
release:
stage: release
@ -85,11 +87,12 @@ release:
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
@ -109,11 +112,9 @@ trigger:
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command tsdoc
- npmci command npm run buildDocs
tags:
- lossless
- docker

24
.vscode/launch.json vendored
View File

@ -2,28 +2,10 @@
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
"type": "node-terminal"
}
]
}

View File

@ -15,7 +15,7 @@
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm"]
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}

View File

@ -7,10 +7,10 @@
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"gitscope": "push.rocks",
"gitrepo": "smarttime",
"shortDescription": "handle time in smart ways",
"npmPackagename": "@pushrocks/smarttime",
"description": "handle time in smart ways",
"npmPackagename": "@push.rocks/smarttime",
"license": "MIT"
}
}

3292
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +1,33 @@
{
"name": "@pushrocks/smarttime",
"name": "@push.rocks/smarttime",
"private": false,
"version": "3.0.17",
"version": "4.0.2",
"description": "handle time in smart ways",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest ./test/)",
"build": "(tsbuild && tsbundle npm)"
"test": "(tstest ./test)",
"build": "(tsbuild --web && tsbundle npm)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.11",
"@gitzone/tsbundle": "^1.0.69",
"@gitzone/tsrun": "^1.2.6",
"@gitzone/tstest": "^1.0.24",
"@pushrocks/tapbundle": "^3.0.9",
"@types/node": "^14.0.5",
"tslint": "^6.1.2",
"tslint-config-prettier": "^1.18.0"
"@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsbundle": "^2.0.8",
"@gitzone/tsrun": "^1.2.42",
"@gitzone/tstest": "^1.0.60",
"@push.rocks/tapbundle": "^5.0.4",
"@types/node": "^20.4.1"
},
"dependencies": {
"@pushrocks/smartdelay": "^2.0.9",
"@pushrocks/smartpromise": "^3.0.2",
"@types/cron": "^1.7.1",
"croner": "^1.1.23",
"dayjs": "^1.8.27",
"is-nan": "^1.3.0"
"@push.rocks/lik": "^6.0.3",
"@push.rocks/smartdelay": "^3.0.2",
"@push.rocks/smartpromise": "^4.0.3",
"croner": "^5.3.4",
"dayjs": "^1.11.9",
"is-nan": "^1.3.2",
"pretty-ms": "^8.0.0"
},
"files": [
"ts/**/*",
@ -40,5 +40,9 @@
"cli.js",
"npmextra.json",
"readme.md"
]
],
"browserslist": [
"last 1 chrome versions"
],
"type": "module"
}

4959
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -8,13 +8,20 @@ handle time in smart ways
* [docs (typedoc)](https://pushrocks.gitlab.io/smarttime/)
## Status for master
[![pipeline status](https://gitlab.com/pushrocks/smarttime/badges/master/pipeline.svg)](https://gitlab.com/pushrocks/smarttime/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smarttime/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smarttime/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@pushrocks/smarttime.svg)](https://www.npmjs.com/package/@pushrocks/smarttime)
[![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smarttime/badge.svg)](https://snyk.io/test/npm/@pushrocks/smarttime)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smarttime/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smarttime/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smarttime)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smarttime)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smarttime)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smarttime)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smarttime)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage
@ -29,7 +36,7 @@ This class provides scheduling of functions with a cron syntax
```typescript
import { CronManager } from '@pushrocks/smarrtime';
const cronManagerInstance = new CronManager();
cronManagerInstance.addConrjob('* * * * * *', async () => {
cronManagerInstance.addCronjob('* * * * * *', async () => {
console.log('hello'); // will log 'hello' to console once every second;
});
cronManagerInstance.start();
@ -44,7 +51,6 @@ import { ExtendedDate } from '@pushrocks/smarttime'
const myDate: Date = ExtendedDate.fromEuropeanDate('8.6.2018')
```
## Contribution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)

View File

@ -1,35 +1,35 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smarttime from '../ts/index.js';
// Test TimeStamp class
let testTimeStamp: smarttime.TimeStamp;
let testTimeStamp2: smarttime.TimeStamp;
tap.test('should create valid testTimeStamp instance', async tools => {
tap.test('should create valid testTimeStamp instance', async (tools) => {
testTimeStamp = new smarttime.TimeStamp();
await tools.delayFor(2);
testTimeStamp2 = new smarttime.TimeStamp();
expect(testTimeStamp).to.be.instanceof(smarttime.TimeStamp);
expect(testTimeStamp).to.be.instanceof(smarttime.TimeStamp);
expect(testTimeStamp).toBeInstanceOf(smarttime.TimeStamp);
expect(testTimeStamp).toBeInstanceOf(smarttime.TimeStamp);
});
tap.test('should have valid linuxtime', async () => {
// tslint:disable-next-line:no-unused-expression
expect(testTimeStamp.isOlderThan(testTimeStamp2)).to.be.true;
expect(testTimeStamp.isOlderThan(testTimeStamp2)).toBeTrue();
// tslint:disable-next-line:no-unused-expression
expect(testTimeStamp.isYoungerThanOtherTimeStamp(testTimeStamp2)).to.be.false;
expect(testTimeStamp.isYoungerThanOtherTimeStamp(testTimeStamp2)).toBeFalse();
});
let testHrtMeasurement: smarttime.HrtMeasurement;
// Test HrtMeasurement
tap.test('should create valid HrtMeasurements', async tools => {
tap.test('should create valid HrtMeasurements', async (tools) => {
testHrtMeasurement = new smarttime.HrtMeasurement();
testHrtMeasurement.start();
await tools.delayFor(20);
testHrtMeasurement.stop();
expect(testHrtMeasurement.milliSeconds).to.be.greaterThan(19);
expect(testHrtMeasurement.milliSeconds).to.be.lessThan(25);
expect(testHrtMeasurement.milliSeconds).toBeGreaterThan(19);
expect(testHrtMeasurement.milliSeconds).toBeLessThan(25);
});
// check units
@ -41,7 +41,7 @@ tap.test('should combine units', async () => {
weeks: 2,
days: 2,
hours: 2,
minutes: 2
minutes: 2,
});
// tslint:disable-next-line:no-console
console.log(computedTime);

View File

@ -0,0 +1,60 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as smarttime from '../ts/index.js';
let testCronManager: smarttime.CronManager;
tap.test('should create a valid instance of cronmanager', async () => {
testCronManager = new smarttime.CronManager();
expect(testCronManager).toBeInstanceOf(smarttime.CronManager);
});
tap.test('should create a valid cronJon', async (tools) => {
const done = tools.defer();
const done2 = tools.defer();
const done3 = tools.defer();
let counter = 0;
let counter2 = 0;
let counter3 = 0;
const cronJob = testCronManager.addCronjob('*/2 * * * * *', async () => {
if (counter === 5) {
testCronManager.removeCronjob(cronJob);
done.resolve();
}
counter++;
console.log(`${new Date().getSeconds()} hey ${counter} -> runs every 2 seconds`);
});
const cronJob2 = testCronManager.addCronjob('*/3 * * * * *', async () => {
if (counter2 === 5) {
testCronManager.removeCronjob(cronJob2);
done2.resolve();
}
counter2++;
console.log(`${new Date().getSeconds()} hey ${counter2} -> runs every 3 seconds`);
});
const cronJob3 = testCronManager.addCronjob('*/4 * * * * *', async () => {
if (counter3 === 5) {
done3.resolve();
}
counter3++;
console.log(`${new Date().getSeconds()} hey ${counter3} -> runs every 4 seconds`);
});
testCronManager.start();
await done.promise;
await done2.promise;
await done3.promise;
testCronManager.stop();
testCronManager.removeCronjob(cronJob3);
});
tap.test('runs every full minute', async (tools) => {
const done = tools.defer();
const cronJob = testCronManager.addCronjob('0 * * * * *', async () => {
done.resolve();
});
testCronManager.start();
await done.promise;
testCronManager.stop();
});
tap.start();

View File

@ -1,27 +0,0 @@
import { tap, expect } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index';
let testCronManager: smarttime.CronManager;
tap.test('should create a valid instance of cronmanager', async () => {
testCronManager = new smarttime.CronManager();
expect(testCronManager).to.be.instanceOf(smarttime.CronManager);
});
tap.test('should create a valid cronJon', async tools => {
const done = tools.defer();
let counter = 0;
testCronManager.addCronjob('*/2 * * * * *', () => {
if (counter === 10) {
done.resolve();
}
counter++;
console.log(`hey ${counter}`);
});
testCronManager.start();
await done.promise;
testCronManager.stop();
});
tap.start();

View File

@ -1,6 +1,11 @@
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smarttime from '../ts/index';
import * as smarttime from '../ts/index.js';
tap.test('should create a valid JavaScript Date', async () => {
const extendedDate = new smarttime.ExtendedDate(Date.now());
console.log(extendedDate);
});
tap.test('should create a valid JavaScript Date from European TimeStamp', async () => {
const extendedDate = smarttime.ExtendedDate.fromEuropeanDate('1.6.2018');
@ -18,7 +23,12 @@ tap.test('should create a date and time with European Format', async () => {
tap.test('should create a European date string', async () => {
const extendedDate = smarttime.ExtendedDate.fromHyphedDate('2018-02-13');
expect(extendedDate.exportToEuropeanDate()).to.equal('13.02.2018');
expect(extendedDate.exportToEuropeanDate()).toEqual('13.02.2018');
});
tap.test('should format a date', async () => {
const extendedDate = new smarttime.ExtendedDate(Date.now());
console.log(extendedDate.format('YYYY-MM-DD - hh:mm'));
});
tap.start();

View File

@ -1,13 +1,13 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@push.rocks/tapbundle';
import { Timer } from '../ts/index';
import { Timer } from '../ts/index.js';
let testTimer: Timer;
tap.test('should create a valid timer', async () => {
testTimer = new Timer(1000);
expect(testTimer).to.be.instanceof(Timer);
expect(testTimer).toBeInstanceOf(Timer);
});
tap.test('should start timer', async () => {

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smarttime',
version: '4.0.2',
description: 'handle time in smart ways'
}

View File

@ -1,7 +1,8 @@
export * from './smarttime.classes.cronmanager';
export * from './smarttime.classes.extendeddate';
export * from './smarttime.classes.hrtmeasurement';
export * from './smarttime.classes.interval';
export * from './smarttime.classes.timer';
export * from './smarttime.classes.timestamp';
export * from './smarttime.units';
export * from './smarttime.classes.cronmanager.js';
export * from './smarttime.classes.cronjob.js';
export * from './smarttime.classes.extendeddate.js';
export * from './smarttime.classes.hrtmeasurement.js';
export * from './smarttime.classes.interval.js';
export * from './smarttime.classes.timer.js';
export * from './smarttime.classes.timestamp.js';
export * from './smarttime.units.js';

View File

@ -1,10 +1,14 @@
import * as plugins from './smarttime.plugins';
import { CronManager } from './smarttime.classes.cronmanager';
import * as plugins from './smarttime.plugins.js';
import { CronManager } from './smarttime.classes.cronmanager.js';
export type TJobFunction = (() => void) | (() => Promise<any>);
import { CronParser } from './smarttime.classes.cronparser.js';
export type TJobFunction =
| ((triggerTimeArg?: number) => void)
| ((triggerTimeArg?: number) => Promise<any>);
export class CronJob {
public croner;
public cronParser: plugins.croner;
public status: 'started' | 'stopped' | 'initial' = 'initial';
public cronExpression: string;
public jobFunction: TJobFunction;
@ -13,7 +17,7 @@ export class CronJob {
constructor(cronManager: CronManager, cronExpressionArg: string, jobFunction: TJobFunction) {
this.cronExpression = cronExpressionArg;
this.jobFunction = jobFunction;
this.croner = plugins.croner(this.cronExpression);
this.cronParser = plugins.croner(cronExpressionArg);
}
/**
@ -21,15 +25,29 @@ export class CronJob {
*/
public checkExecution(): number {
if (this.nextExecutionUnix === 0) {
this.nextExecutionUnix = this.croner.msToNext();
this.getNextExecutionTime();
}
if (Date.now() > this.nextExecutionUnix) {
this.jobFunction();
this.nextExecutionUnix = this.croner.msToNext();
const maybePromise = this.jobFunction(this.nextExecutionUnix);
if (maybePromise instanceof Promise) {
maybePromise.catch((e) => console.log(e));
}
this.nextExecutionUnix = this.getNextExecutionTime();
}
return this.nextExecutionUnix;
}
public getNextExecutionTime() {
return (this.nextExecutionUnix = Date.now() + this.getTimeToNextExecution());
}
/**
* gets the time to next execution
*/
public getTimeToNextExecution() {
return this.cronParser.msToNext();
}
public start() {
this.status = 'started';
}

View File

@ -1,58 +1,84 @@
import * as plugins from './smarttime.plugins';
import { CronJob } from './smarttime.classes.cronjob';
import * as plugins from './smarttime.plugins.js';
import { CronJob, TJobFunction } from './smarttime.classes.cronjob.js';
import { getMilliSecondsAsHumanReadableString } from './smarttime.units.js';
export class CronManager {
public executionTimeout: plugins.smartdelay.Timeout<void>;
public status: 'started' | 'stopped' = 'stopped';
public cronjobs: CronJob[] = [];
public cronjobs = new plugins.lik.ObjectMap<CronJob>();
constructor() {}
public addCronjob(cronIdentifierArg: string, cronFunctionArg: () => any) {
public addCronjob(cronIdentifierArg: string, cronFunctionArg: TJobFunction) {
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
this.cronjobs.push(newCronJob);
this.cronjobs.add(newCronJob);
if (this.status === 'started') {
newCronJob.start();
}
return newCronJob;
}
public removeCronjob(cronjobArg: CronJob) {
cronjobArg.stop();
this.cronjobs.remove(cronjobArg);
}
/**
* starts the cronjob
*/
public start() {
this.status = 'started';
for (const cronJob of this.cronjobs) {
cronJob.start();
}
this.executionTimeout = new plugins.smartdelay.Timeout(0);
// recursion
const runCheckExecution = () => {
console.log(`Next CronJob scheduled in ${this.executionTimeout.getTimeLeft()} milliseconds`);
this.executionTimeout.promise.then(() => {
let timeToNextOverallExecution: number;
for (const cronJob of this.cronjobs) {
const timeToNextJobExecution = cronJob.checkExecution();
if (timeToNextJobExecution < timeToNextOverallExecution || !timeToNextOverallExecution) {
timeToNextOverallExecution = timeToNextJobExecution;
if (this.status !== 'started') {
this.status = 'started';
for (const cronJob of this.cronjobs.getArray()) {
cronJob.start();
}
const runCronCycle = async () => {
this.executionTimeout = new plugins.smartdelay.Timeout(0);
do {
let nextRunningCronjob: CronJob;
for (const cronJob of this.cronjobs.getArray()) {
cronJob.checkExecution();
if (
!nextRunningCronjob ||
cronJob.getTimeToNextExecution() < nextRunningCronjob.getTimeToNextExecution()
) {
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');
}
}
this.executionTimeout = new plugins.smartdelay.Timeout(timeToNextOverallExecution);
runCheckExecution();
});
};
runCheckExecution();
await this.executionTimeout.promise;
} while (this.status === 'started');
};
runCronCycle();
}
}
/**
* stops all cronjobs
*/
public stop() {
this.status = 'stopped';
this.executionTimeout.cancel();
for (const cron of this.cronjobs) {
if (this.status === 'started') {
this.status = 'stopped';
this.executionTimeout.cancel();
} else {
console.log(`You tried to stop a CronManager that was not actually started.`);
}
for (const cron of this.cronjobs.getArray()) {
cron.stop();
}
}

View File

@ -0,0 +1,88 @@
import * as plugins from './smarttime.plugins.js';
export class CronParser {
public cronExpression: string;
public get cronArray() {
return this.cronExpression.split(' ');
}
constructor(cronExpressionArg: string) {
this.cronExpression = cronExpressionArg;
if (this.cronArray.length < 6) {
throw new Error('CronParser needs second level accuracy');
}
}
private getNextPartMatch(cronPart: string, startValue: number, moduloArg: number) {
if (cronPart === '*') {
return startValue;
}
if (cronPart.includes('/')) {
const every = parseInt(cronPart.split('/')[1], 10);
const findEvenMatch = (recursionStartArg: number): number => {
if (recursionStartArg % every === 0) {
return recursionStartArg;
} else {
return findEvenMatch(recursionStartArg + 1);
}
};
return findEvenMatch(startValue);
}
if (parseInt(cronPart, 10) || cronPart === '0') {
const match = parseInt(cronPart, 10);
return match;
}
}
public msToNext() {
const cronArray = this.cronArray;
const secondExpression = cronArray[0];
const minuteExpression = cronArray[1];
const hourExpression = cronArray[2];
const dayExpression = cronArray[3];
const monthExpression = cronArray[4];
const yearExpression = cronArray[5];
let currentDate = new Date();
let currentSecond = currentDate.getSeconds() + 1;
let currentMinute = currentDate.getMinutes();
let currentHour = currentDate.getHours();
let currentDay = currentDate.getDate();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
const targetSecond = this.getNextPartMatch(secondExpression, currentSecond, 59);
if (targetSecond < currentSecond) {
currentMinute = (currentMinute + 1) % 59;
}
const targetMinute = this.getNextPartMatch(minuteExpression, currentMinute, 59);
if (targetMinute < currentMinute) {
currentHour = (currentHour + 1) % 23;
}
const targetHour = this.getNextPartMatch(hourExpression, currentHour, 23);
if (targetHour < currentHour) {
currentDay = (currentDay + 1) % 30;
}
const targetDay = currentDay;
if (targetDay < currentDay) {
currentMonth = (currentMonth + 1) % 11;
}
const targetMonth = currentMonth;
if (targetMonth < currentMonth) {
currentYear = currentYear + 1;
}
const targetYear = currentYear;
const targetDate = new Date(
targetYear,
targetMonth,
targetDay,
targetHour,
targetMinute,
targetSecond
);
const targetTime = targetDate.getTime();
return targetTime - Date.now();
}
}

View File

@ -1,4 +1,5 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
import * as units from './smarttime.units.js';
export type TAvailableZone = 'Europe/Berlin';
@ -72,7 +73,7 @@ export class ExtendedDate extends Date {
// INSTANCE
public timezone: TAvailableZone;
constructor(unixMilli: number) {
constructor(unixMilli: number = Date.now()) {
super(unixMilli);
}
@ -82,6 +83,11 @@ export class ExtendedDate extends Date {
return `${units.dayString}.${units.monthString}.${units.yearString}`;
}
public exportToHyphedSortableDate() {
const units = this.exportToUnits();
return `${units.yearString}-${units.monthString}-${units.dayString}`;
}
/**
* exports units
*/
@ -98,7 +104,7 @@ export class ExtendedDate extends Date {
'September',
'October',
'November',
'December'
'December',
];
const daysArray = [
'Monday',
@ -107,7 +113,7 @@ export class ExtendedDate extends Date {
'Thursday',
'Friday',
'Saturday',
'Sunday'
'Sunday',
];
return {
year: this.getFullYear(),
@ -118,7 +124,28 @@ export class ExtendedDate extends Date {
day: this.getDate(),
dayString: ('0' + this.getDate()).slice(-2),
dayOfTheWeek: this.getDay(),
dayOfTheWeekName: daysArray[this.getDay()]
dayOfTheWeekName: daysArray[this.getDay()],
};
}
public format(formatArg: string) {
return plugins.dayjs(this.getTime()).format(formatArg);
}
/**
* boolean checks
*/
public isToday() {
return plugins.dayjs(this.getTime()).isToday();
}
public lessTimePassedToNow(unitArgs: units.IUnitCombinationArg): boolean {
const maxPassedUnixTime = units.getMilliSecondsFromUnits(unitArgs);
const actualPassedUnixTime = Date.now() - this.getTime();
return actualPassedUnixTime < maxPassedUnixTime;
}
public moreTimePassedToNow(unitArgs: units.IUnitCombinationArg) {
return !this.lessTimePassedToNow(unitArgs);
}
}

View File

@ -4,8 +4,8 @@
export class HrtMeasurement {
public nanoSeconds: number = null;
public milliSeconds: number = null;
private _hrTimeStart = null;
private _hrTimeStopDiff = null;
private _milliStart: number = null;
private _milliDiff: number = null;
private _started: boolean = false;
/**
@ -13,7 +13,7 @@ export class HrtMeasurement {
*/
public start() {
this._started = true;
this._hrTimeStart = process.hrtime();
this._milliStart = Date.now();
}
/**
@ -24,9 +24,9 @@ export class HrtMeasurement {
console.log("Hasn't started yet");
return;
}
this._hrTimeStopDiff = process.hrtime(this._hrTimeStart);
this.nanoSeconds = this._hrTimeStopDiff[0] * 1e9 + this._hrTimeStopDiff[1];
this.milliSeconds = this.nanoSeconds / 1000000;
this._milliDiff = Date.now() - this._milliStart;
this.nanoSeconds = this._milliDiff * 1000;
this.milliSeconds = this._milliDiff;
return this;
}
@ -36,8 +36,8 @@ export class HrtMeasurement {
public reset() {
this.nanoSeconds = null;
this.milliSeconds = null;
this._hrTimeStart = null;
this._hrTimeStopDiff = null;
this._milliStart = null;
this._milliDiff = null;
this._started = false;
}
}

View File

@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
export class Interval {
public status: 'started' | 'stopped' | 'initial' = 'initial';

View File

@ -1,6 +1,6 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
import { TimeStamp } from './smarttime.classes.timestamp';
import { TimeStamp } from './smarttime.classes.timestamp.js';
export type TimerState = 'initiated' | 'started' | 'paused' | 'completed';

View File

@ -1,4 +1,4 @@
import * as plugins from './smarttime.plugins';
import * as plugins from './smarttime.plugins.js';
/**
* TimeStamp
@ -8,7 +8,7 @@ export class TimeStamp {
/**
* returns new TimeStamp from milliseconds
*/
public static fromMilliSeconds(milliSecondsArg) {
public static fromMilliSeconds(milliSecondsArg: number) {
return new TimeStamp(milliSecondsArg);
}
@ -53,6 +53,19 @@ export class TimeStamp {
this.epochtime = Math.floor(this.milliSeconds / 1000);
}
/**
* returns a boolean for wether the timestamp is older than another timestamp
* @param TimeStampArg
* @param tresholdTimeArg
*/
public isOlderThanOtherTimeStamp(TimeStampArg: TimeStamp, tresholdTimeArg: number = 0) {
if (this.milliSeconds < TimeStampArg.milliSeconds - tresholdTimeArg) {
return true;
} else {
return false;
}
}
/**
* Is the current instance older than the argument
* @param TimeStampArg
@ -66,7 +79,7 @@ export class TimeStamp {
}
/**
* returns a boolean for wether a timestamp is younger
* returns a boolean for wether the timestamp is younger than another timestamp
* @param TimeStampArg
* @param tresholdTimeArg
*/

View File

@ -1,11 +1,16 @@
// @pushrocks scope
import * as smartdelay from '@pushrocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise';
import * as lik from '@push.rocks/lik';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartpromise from '@push.rocks/smartpromise';
export { smartdelay, smartpromise };
export { lik, smartdelay, smartpromise };
// third parties
// third parties;
import croner from 'croner';
import dayjs from 'dayjs';
import isToday from 'dayjs/plugin/isToday.js';
import prettyMs from 'pretty-ms';
export { croner, dayjs };
dayjs.extend(isToday);
export { croner, dayjs, prettyMs };

View File

@ -1,3 +1,5 @@
import * as plugins from './smarttime.plugins.js';
export let units = {
years: (timesArg = 1): number => {
return timesArg * 3.154e10;
@ -16,7 +18,7 @@ export let units = {
},
minutes: (timesArg = 1) => {
return timesArg * 60000;
}
},
};
export interface IUnitCombinationArg {
@ -30,7 +32,7 @@ export interface IUnitCombinationArg {
export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
let timeInMilliseconds = 0;
let addMilliSeconds = milliSecondsArg => {
let addMilliSeconds = (milliSecondsArg: number) => {
timeInMilliseconds = timeInMilliseconds + milliSecondsArg;
};
if (combinationArg.years) {
@ -54,3 +56,7 @@ export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
return timeInMilliseconds;
};
export const getMilliSecondsAsHumanReadableString = (milliSecondsArg: number): string => {
return plugins.prettyMs(milliSecondsArg);
};

10
tsconfig.json Normal file
View File

@ -0,0 +1,10 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"esModuleInterop": true
}
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}