Compare commits

...

18 Commits

Author SHA1 Message Date
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
95bf558503 3.0.17 2020-05-27 16:59:27 +00:00
d1ff77d9f5 fix(core): update 2020-05-27 16:59:26 +00:00
b77677b089 3.0.16 2020-05-25 22:21:55 +00:00
5ebd9ce6de fix(core): update 2020-05-25 22:21:55 +00:00
15 changed files with 8825 additions and 777 deletions

21
license Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Lossless GmbH (hello@lossless.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

9360
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{ {
"name": "@pushrocks/smarttime", "name": "@pushrocks/smarttime",
"private": false, "private": false,
"version": "3.0.15", "version": "3.0.24",
"description": "handle time in smart ways", "description": "handle time in smart ways",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
@ -9,25 +9,25 @@
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest ./test/)", "test": "(tstest ./test/)",
"build": "(tsbuild && tsbundle npm)" "build": "(tsbuild --web && tsbundle npm)"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.11", "@gitzone/tsbuild": "^2.1.11",
"@gitzone/tsbundle": "^1.0.69", "@gitzone/tsbundle": "^1.0.72",
"@gitzone/tsrun": "^1.2.6", "@gitzone/tsrun": "^1.2.12",
"@gitzone/tstest": "^1.0.24", "@gitzone/tstest": "^1.0.41",
"@pushrocks/tapbundle": "^3.0.9", "@pushrocks/tapbundle": "^3.2.9",
"@types/node": "^14.0.5", "@types/node": "^14.0.22",
"tslint": "^6.1.2", "tslint": "^6.1.2",
"tslint-config-prettier": "^1.18.0" "tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.6", "@pushrocks/lik": "^4.0.13",
"@pushrocks/smartdelay": "^2.0.10",
"@pushrocks/smartpromise": "^3.0.2", "@pushrocks/smartpromise": "^3.0.2",
"@types/cron": "^1.7.1", "croner": "^1.1.23",
"@types/luxon": "^1.15.1", "dayjs": "^1.8.29",
"cron-parser": "^2.14.0", "is-nan": "^1.3.0"
"luxon": "^1.16.0"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
@ -40,5 +40,8 @@
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
],
"browserslist": [
"last 1 chrome versions"
] ]
} }

View File

@ -8,13 +8,20 @@ handle time in smart ways
* [docs (typedoc)](https://pushrocks.gitlab.io/smarttime/) * [docs (typedoc)](https://pushrocks.gitlab.io/smarttime/)
## Status for master ## 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) Status Category | Status Badge
[![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) GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smarttime/badges/master/pipeline.svg)](https://lossless.cloud)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smarttime/badges/master/coverage.svg)](https://lossless.cloud)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smarttime)](https://lossless.cloud)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/) 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 ## Usage
@ -44,7 +51,6 @@ import { ExtendedDate } from '@pushrocks/smarttime'
const myDate: Date = ExtendedDate.fromEuropeanDate('8.6.2018') const myDate: Date = ExtendedDate.fromEuropeanDate('8.6.2018')
``` ```
## Contribution ## 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). :) 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

@ -0,0 +1,27 @@
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

@ -9,10 +9,10 @@ tap.test('should create a valid instance of cronmanager', async () => {
expect(testCronManager).to.be.instanceOf(smarttime.CronManager); expect(testCronManager).to.be.instanceOf(smarttime.CronManager);
}); });
tap.test('should create a valid cronJon', async tools => { tap.test('should create a valid cronJon', async (tools) => {
const done = tools.defer(); const done = tools.defer();
let counter = 0; let counter = 0;
testCronManager.addCronjob('* * * * * *', () => { testCronManager.addCronjob('*/2 * * * * *', () => {
if (counter === 10) { if (counter === 10) {
done.resolve(); done.resolve();
} }

View File

@ -5,7 +5,7 @@ import * as smarttime from '../ts/index';
// Test TimeStamp class // Test TimeStamp class
let testTimeStamp: smarttime.TimeStamp; let testTimeStamp: smarttime.TimeStamp;
let testTimeStamp2: 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(); testTimeStamp = new smarttime.TimeStamp();
await tools.delayFor(2); await tools.delayFor(2);
testTimeStamp2 = new smarttime.TimeStamp(); testTimeStamp2 = new smarttime.TimeStamp();
@ -23,7 +23,7 @@ tap.test('should have valid linuxtime', async () => {
let testHrtMeasurement: smarttime.HrtMeasurement; let testHrtMeasurement: smarttime.HrtMeasurement;
// Test HrtMeasurement // Test HrtMeasurement
tap.test('should create valid HrtMeasurements', async tools => { tap.test('should create valid HrtMeasurements', async (tools) => {
testHrtMeasurement = new smarttime.HrtMeasurement(); testHrtMeasurement = new smarttime.HrtMeasurement();
testHrtMeasurement.start(); testHrtMeasurement.start();
await tools.delayFor(20); await tools.delayFor(20);
@ -41,7 +41,7 @@ tap.test('should combine units', async () => {
weeks: 2, weeks: 2,
days: 2, days: 2,
hours: 2, hours: 2,
minutes: 2 minutes: 2,
}); });
// tslint:disable-next-line:no-console // tslint:disable-next-line:no-console
console.log(computedTime); console.log(computedTime);

View File

@ -1,10 +1,8 @@
import * as plugins from './smarttime.plugins';
export * from './smarttime.classes.cronmanager'; export * from './smarttime.classes.cronmanager';
export * from './smarttime.classes.cronjob';
export * from './smarttime.classes.extendeddate'; export * from './smarttime.classes.extendeddate';
export * from './smarttime.classes.hrtmeasurement'; export * from './smarttime.classes.hrtmeasurement';
export * from './smarttime.classes.interval';
export * from './smarttime.classes.timer'; export * from './smarttime.classes.timer';
export * from './smarttime.classes.timestamp'; export * from './smarttime.classes.timestamp';
export * from './smarttime.units'; export * from './smarttime.units';
export { luxon } from './smarttime.plugins';

View File

@ -4,48 +4,37 @@ import { CronManager } from './smarttime.classes.cronmanager';
export type TJobFunction = (() => void) | (() => Promise<any>); export type TJobFunction = (() => void) | (() => Promise<any>);
export class CronJob { export class CronJob {
public croner;
public status: 'started' | 'stopped' | 'initial' = 'initial'; public status: 'started' | 'stopped' | 'initial' = 'initial';
public cronExpression: string; public cronExpression: string;
public jobFunction: TJobFunction; public jobFunction: TJobFunction;
private cronInterval = plugins.cronParser.parseExpression('* * * * * *');
private nextExecutionUnix: number = 0; private nextExecutionUnix: number = 0;
constructor(cronManager: CronManager, cronExpressionArg: string, jobFunction: TJobFunction) { constructor(cronManager: CronManager, cronExpressionArg: string, jobFunction: TJobFunction) {
this.cronExpression = cronExpressionArg; this.cronExpression = cronExpressionArg;
this.jobFunction = jobFunction; this.jobFunction = jobFunction;
this.croner = plugins.croner(this.cronExpression);
} }
/** /**
* checks wether the cronjob needs to be executed * checks wether the cronjob needs to be executed
*/ */
public checkExecution() { public checkExecution(): number {
if (this.nextExecutionUnix === 0) { if (this.nextExecutionUnix === 0) {
this.nextExecutionUnix = this.cronInterval this.nextExecutionUnix = this.croner.msToNext();
.next()
.toDate()
.getTime();
return;
} }
if (Date.now() > this.nextExecutionUnix) { if (Date.now() > this.nextExecutionUnix) {
this.jobFunction(); this.jobFunction();
this.nextExecutionUnix = this.cronInterval this.nextExecutionUnix = this.croner.msToNext();
.next()
.toDate()
.getTime();
} }
return this.nextExecutionUnix;
} }
public start() { public start() {
this.cronInterval = this.getCronInterval();
this.status = 'started'; this.status = 'started';
} }
public stop() { public stop() {
this.status = 'stopped'; this.status = 'stopped';
} }
private getCronInterval() {
return plugins.cronParser.parseExpression(this.cronExpression);
}
} }

View File

@ -1,39 +1,63 @@
import * as plugins from './smarttime.plugins'; import * as plugins from './smarttime.plugins';
import { CronJob } from './smarttime.classes.cronjob'; import { CronJob } from './smarttime.classes.cronjob';
import { Timer } from './smarttime.classes.timer';
import { Interval } from './smarttime.classes.interval';
export class CronManager { export class CronManager {
public cronInterval = new Interval(1000); public executionTimeout: plugins.smartdelay.Timeout<void>;
public status: 'started' | 'stopped' = 'stopped'; public status: 'started' | 'stopped' = 'stopped';
public cronjobs: CronJob[] = []; public cronjobs = new plugins.lik.ObjectMap<CronJob>();
constructor() { constructor() {}
this.cronInterval.addIntervalJob(() => {
for (const cronJob of this.cronjobs) {
cronJob.checkExecution();
}
});
}
public addCronjob(cronIdentifierArg: string, cronFunctionArg: () => any) { public addCronjob(cronIdentifierArg: string, cronFunctionArg: () => any) {
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg); const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
this.cronjobs.push(newCronJob); this.cronjobs.add(newCronJob);
if (this.status === 'started') { if (this.status === 'started') {
newCronJob.start(); newCronJob.start();
} }
return newCronJob;
}
public removeCronjob(cronjobArg: CronJob) {
cronjobArg.stop();
this.cronjobs.remove(cronjobArg);
} }
/** /**
* starts the cronjob * starts the cronjob
*/ */
public start() { public start() {
if (this.status !== 'started') {
this.status = 'started'; this.status = 'started';
for (const cron of this.cronjobs) { for (const cronJob of this.cronjobs.getArray()) {
cron.start(); 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.getArray()) {
const timeToNextJobExecution = cronJob.checkExecution();
if (
timeToNextJobExecution < timeToNextOverallExecution ||
!timeToNextOverallExecution
) {
timeToNextOverallExecution = timeToNextJobExecution;
}
}
this.executionTimeout = new plugins.smartdelay.Timeout(timeToNextOverallExecution);
runCheckExecution();
});
};
runCheckExecution();
} }
this.cronInterval.start();
} }
/** /**
@ -41,9 +65,9 @@ export class CronManager {
*/ */
public stop() { public stop() {
this.status = 'stopped'; this.status = 'stopped';
for (const cron of this.cronjobs) { this.executionTimeout.cancel();
for (const cron of this.cronjobs.getArray()) {
cron.stop(); cron.stop();
} }
this.cronInterval.stop();
} }
} }

View File

@ -26,12 +26,12 @@ export class ExtendedDate extends Date {
public static fromEuropeanDate(europeanDate: string) { public static fromEuropeanDate(europeanDate: string) {
const dateArray = /(.*)\.(.*)\.(.*)/.exec(europeanDate); const dateArray = /(.*)\.(.*)\.(.*)/.exec(europeanDate);
const luxonDate = plugins.luxon.DateTime.utc( const date = new Date(
parseFloat(dateArray[3]), // year parseFloat(dateArray[3]), // year
parseFloat(dateArray[2]), // month parseFloat(dateArray[2]) - 1, // month
parseFloat(dateArray[1]) // day parseFloat(dateArray[1]) // day
); );
const unixMilli = luxonDate.toMillis(); const unixMilli = date.getTime();
return new ExtendedDate(unixMilli); return new ExtendedDate(unixMilli);
} }
@ -64,10 +64,8 @@ export class ExtendedDate extends Date {
const dateTimeString = `${dateArray[3]}-${sliceDate(dateArray[2])}-${sliceDate( const dateTimeString = `${dateArray[3]}-${sliceDate(dateArray[2])}-${sliceDate(
dateArray[1] dateArray[1]
)}T${timeArg}`; )}T${timeArg}`;
const luxonDate = plugins.luxon.DateTime.fromISO(dateTimeString, { const date = plugins.dayjs(dateTimeString);
zone: zoneArg const unixMilli = date.toDate().getTime();
});
const unixMilli = luxonDate.toMillis();
return new ExtendedDate(unixMilli); return new ExtendedDate(unixMilli);
} }
@ -100,7 +98,7 @@ export class ExtendedDate extends Date {
'September', 'September',
'October', 'October',
'November', 'November',
'December' 'December',
]; ];
const daysArray = [ const daysArray = [
'Monday', 'Monday',
@ -109,7 +107,7 @@ export class ExtendedDate extends Date {
'Thursday', 'Thursday',
'Friday', 'Friday',
'Saturday', 'Saturday',
'Sunday' 'Sunday',
]; ];
return { return {
year: this.getFullYear(), year: this.getFullYear(),
@ -120,7 +118,7 @@ export class ExtendedDate extends Date {
day: this.getDate(), day: this.getDate(),
dayString: ('0' + this.getDate()).slice(-2), dayString: ('0' + this.getDate()).slice(-2),
dayOfTheWeek: this.getDay(), dayOfTheWeek: this.getDay(),
dayOfTheWeekName: daysArray[this.getDay()] dayOfTheWeekName: daysArray[this.getDay()],
}; };
} }
} }

View File

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

View File

@ -4,7 +4,10 @@ export class Interval {
public status: 'started' | 'stopped' | 'initial' = 'initial'; public status: 'started' | 'stopped' | 'initial' = 'initial';
private statusAuthorization: any = null; private statusAuthorization: any = null;
// timings
public intervalMilliseconds: number; public intervalMilliseconds: number;
public nextIntervalMillisenconds: number;
public intervalJobs: Array<() => any> = []; public intervalJobs: Array<() => any> = [];
constructor(intervalMillisencondsArg: number) { constructor(intervalMillisencondsArg: number) {
this.intervalMilliseconds = intervalMillisencondsArg; this.intervalMilliseconds = intervalMillisencondsArg;

View File

@ -1,11 +1,12 @@
// @pushrocks scope // @pushrocks scope
import * as lik from '@pushrocks/lik';
import * as smartdelay from '@pushrocks/smartdelay'; import * as smartdelay from '@pushrocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise'; import * as smartpromise from '@pushrocks/smartpromise';
export { smartdelay, smartpromise }; export { lik, smartdelay, smartpromise };
// third parties // third parties
import cronParser from 'cron-parser'; import croner from 'croner';
import * as luxon from 'luxon'; import dayjs from 'dayjs';
export { cronParser, luxon }; export { croner, dayjs };

View File

@ -16,7 +16,7 @@ export let units = {
}, },
minutes: (timesArg = 1) => { minutes: (timesArg = 1) => {
return timesArg * 60000; return timesArg * 60000;
} },
}; };
export interface IUnitCombinationArg { export interface IUnitCombinationArg {
@ -30,7 +30,7 @@ export interface IUnitCombinationArg {
export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => { export let getMilliSecondsFromUnits = (combinationArg: IUnitCombinationArg) => {
let timeInMilliseconds = 0; let timeInMilliseconds = 0;
let addMilliSeconds = milliSecondsArg => { let addMilliSeconds = (milliSecondsArg) => {
timeInMilliseconds = timeInMilliseconds + milliSecondsArg; timeInMilliseconds = timeInMilliseconds + milliSecondsArg;
}; };
if (combinationArg.years) { if (combinationArg.years) {