Compare commits

...

34 Commits

Author SHA1 Message Date
4d0fb3eb30 3.0.14 2020-05-25 21:49:08 +00:00
3f0b230d23 fix(core): update 2020-05-25 21:49:08 +00:00
0c0b08e2be 3.0.13 2020-05-25 21:45:44 +00:00
dd722146f4 fix(core): update 2020-05-25 21:45:43 +00:00
c968e156ae 3.0.12 2019-06-18 14:45:07 +02:00
b5509711e7 fix(core): update 2019-06-18 14:45:07 +02:00
f8540b8076 3.0.11 2019-06-18 14:38:57 +02:00
30d18db4af fix(core): update 2019-06-18 14:38:57 +02:00
388649659c 3.0.10 2019-06-18 11:58:36 +02:00
e8ff289a9a fix(core): update 2019-06-18 11:58:36 +02:00
a5deb25bfb 3.0.9 2019-06-17 17:19:55 +02:00
ce2d1b278b fix(core): update 2019-06-17 17:19:54 +02:00
aa16e5d5bb 3.0.8 2019-06-17 16:54:39 +02:00
f221e9c0fa fix(core): update 2019-06-17 16:54:39 +02:00
9935396f2d 3.0.7 2019-04-10 14:37:39 +02:00
1bc379daa5 3.0.6 2019-04-10 14:06:21 +02:00
f9b81fc801 fix(core): update 2019-04-10 14:06:20 +02:00
6d8e39f11b 3.0.6 2019-04-10 11:34:30 +02:00
cff5b5a7f4 fix(core): update 2019-04-10 11:34:30 +02:00
f6be9b71f1 3.0.5 2018-11-23 19:26:42 +01:00
9c2d584170 fix(core): update 2018-11-23 19:26:41 +01:00
10bff069c1 3.0.4 2018-11-23 18:48:08 +01:00
8f6272eca4 fix(core): update 2018-11-23 18:48:07 +01:00
f02df7789c 3.0.3 2018-11-23 18:29:38 +01:00
d720b8b084 fix(core): update 2018-11-23 18:29:38 +01:00
6bca8557f9 3.0.2 2018-10-21 17:32:03 +02:00
f0a5e18335 fix(ExtendedDate): now respects single digit dates 2018-10-21 17:32:03 +02:00
57fbdb4a70 update 2018-10-21 17:23:58 +02:00
4a56527f7d 3.0.1 2018-10-21 12:12:45 +02:00
2a14d928a8 fix(date): now supports date and time 2018-10-21 12:12:44 +02:00
f161f71c4e 3.0.0 2018-10-17 01:42:36 +02:00
ed1f79caa4 BREAKING CHANGE(deps): remove moment and use luxon 2018-10-17 01:42:36 +02:00
539bbc1568 2.0.2 2018-07-13 00:03:08 +02:00
7d4bf05289 fix(dependencies): leaner dependencies 2018-07-13 00:03:08 +02:00
21 changed files with 3599 additions and 345 deletions

19
.gitignore vendored
View File

@ -1,5 +1,22 @@
.nogit/ .nogit/
node_modules/
# artifacts
coverage/ coverage/
public/ public/
pages/ pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_web/
dist_serve/
dist_ts_web/
# custom

View File

@ -1,4 +1,4 @@
# gitzone standard # gitzone ci_default
image: hosttoday/ht-docker-node:npmci image: hosttoday/ht-docker-node:npmci
cache: cache:
@ -26,6 +26,7 @@ mirror:
snyk: snyk:
stage: security stage: security
script: script:
- npmci npm prepare
- npmci command npm install -g snyk - npmci command npm install -g snyk
- npmci command npm install --ignore-scripts - npmci command npm install --ignore-scripts
- npmci command snyk test - npmci command snyk test
@ -36,21 +37,11 @@ snyk:
# ==================== # ====================
# test stage # test stage
# ==================== # ====================
testLEGACY:
stage: test
script:
- npmci node install legacy
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
allow_failure: true
testLTS: testLTS:
stage: test stage: test
script: script:
- npmci npm prepare
- npmci node install lts - npmci node install lts
- npmci npm install - npmci npm install
- npmci npm test - npmci npm test
@ -62,6 +53,7 @@ testLTS:
testSTABLE: testSTABLE:
stage: test stage: test
script: script:
- npmci npm prepare
- npmci node install stable - npmci node install stable
- npmci npm install - npmci npm install
- npmci npm test - npmci npm test
@ -86,19 +78,11 @@ release:
# ==================== # ====================
codequality: codequality:
stage: metadata stage: metadata
image: docker:stable
allow_failure: true allow_failure: true
services:
- docker:stable-dind
script: script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/') - npmci command npm install -g tslint typescript
- docker run - npmci npm install
--env SOURCE_CODE="$PWD" - npmci command "tslint -c tslint.json ./ts/**/*.ts"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags: tags:
- docker - docker
- priv - priv
@ -117,8 +101,10 @@ pages:
image: hosttoday/ht-docker-node:npmci image: hosttoday/ht-docker-node:npmci
stage: metadata stage: metadata
script: script:
- npmci command npm install -g npmpage - npmci command npm install -g @gitzone/tsdoc
- npmci command npmpage - npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags: tags:
- docker - docker
- notpriv - notpriv
@ -128,3 +114,4 @@ pages:
expire_in: 1 week expire_in: 1 week
paths: paths:
- public - public
allow_failure: true

View File

@ -1,8 +1,17 @@
{ {
"npmci": { "npmci": {
"npmGlobalTools": [ "npmGlobalTools": [],
"npmts"
],
"npmAccessLevel": "public" "npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"gitrepo": "smarttime",
"shortDescription": "handle time in smart ways",
"npmPackagename": "@pushrocks/smarttime",
"license": "MIT"
}
} }
} }

3373
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,42 @@
{ {
"name": "@pushrocks/smarttime", "name": "@pushrocks/smarttime",
"private": false, "private": false,
"version": "2.0.1", "version": "3.0.14",
"description": "handle timeformats in smart ways", "description": "handle time in smart ways",
"main": "dist/index.js", "main": "dist_ts/index.js",
"typings": "dist/index.d.ts", "typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tsrun ./test/test.ts)", "test": "(tstest ./test/)",
"build": "(npmts)" "build": "(tsbuild && tsbundle npm)"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsrun": "^1.0.5", "@gitzone/tsbuild": "^2.1.11",
"@types/node": "^9.4.7", "@gitzone/tsbundle": "^1.0.69",
"tapbundle": "^2.0.0" "@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"
}, },
"dependencies": { "dependencies": {
"moment": "^2.21.0", "@pushrocks/smartdelay": "^2.0.6",
"smartdelay": "^1.0.4", "@pushrocks/smartpromise": "^3.0.2",
"smartq": "^1.1.6" "@types/cron": "^1.7.1",
} "@types/luxon": "^1.15.1",
"cron-parser": "^2.14.0",
"luxon": "^1.16.0"
},
"files": [
"ts/*",
"ts_web/*",
"dist/*",
"dist_web/*",
"assets/*",
"cli.js",
"npmextra.json",
"readme.md"
]
} }

View File

@ -1,33 +1,50 @@
# smarttime # @pushrocks/smarttime
handle time in smart ways
handle timeformats in smart ways ## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smarttime)
## Availabililty * [gitlab.com (source)](https://gitlab.com/pushrocks/smarttime)
* [github.com (source mirror)](https://github.com/pushrocks/smarttime)
[![npm](https://pushrocks.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smarttime) * [docs (typedoc)](https://pushrocks.gitlab.io/smarttime/)
[![git](https://pushrocks.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/pushrocks/smarttime)
[![git](https://pushrocks.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smarttime)
[![docs](https://pushrocks.gitlab.io/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smarttime/)
## Status for master ## Status for master
[![build status](https://gitlab.com/pushrocks/smarttime/badges/master/build.svg)](https://gitlab.com/pushrocks/smarttime/commits/master)
[![build status](https://GitLab.com/pushrocks/smarttime/badges/master/build.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)
[![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)
[![npm downloads per month](https://img.shields.io/npm/dm/smarttime.svg)](https://www.npmjs.com/package/smarttime) [![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smarttime/badge.svg)](https://snyk.io/test/npm/@pushrocks/smarttime)
[![Dependency Status](https://david-dm.org/pushrocks/smarttime.svg)](https://david-dm.org/pushrocks/smarttime) [![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smarttime/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smarttime/master/dependencies/npm) [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smarttime/badges/code.svg)](https://www.bithound.io/github/pushrocks/smarttime) [![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage ## Usage
Use TypeScript for best in class instellisense. Use TypeScript for best in class instellisense.
For further information read the linked docs at the top of this README. Smarttime offers smart ways to deal with time.
### class CronManager
This class provides scheduling of functions with a cron syntax
```typescript
import { CronManager } from '@pushrocks/smarrtime';
const cronManagerInstance = new CronManager();
cronManagerInstance.addConrjob('* * * * * *', async () => {
console.log('hello'); // will log 'hello' to console once every second;
})
cronManagerInstance.start();
```
### class ExtendedDate
This class offers static functions to create zone specific JavaScript dates from European formated time strings.
```TypeScript
import { ExtendedDate } from '@pushrocks/smarttime'
const myDate: Date = ExtendedDate.fromEuropeanDate('8.6.2018')
```
For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html) | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks) [![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

27
test/test.cronmanager.ts Normal file
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('* * * * * *', () => {
if (counter === 10) {
done.resolve();
}
counter++;
console.log(`hey ${counter}`);
});
testCronManager.start();
await done.promise;
testCronManager.stop();
});
tap.start();

24
test/test.extendeddate.ts Normal file
View File

@ -0,0 +1,24 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index';
tap.test('should create a valid JavaScript Date from European TimeStamp', async () => {
const extendedDate = smarttime.ExtendedDate.fromEuropeanDate('1.6.2018');
console.log(extendedDate);
});
tap.test('should create a date and time with European Format', async () => {
const extendedDate = smarttime.ExtendedDate.fromEuropeanDateAndTime(
'9.8.2018',
'08:00:00',
'Europe/Berlin'
);
console.log(extendedDate);
});
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');
});
tap.start();

View File

@ -1,5 +1,5 @@
// tslint:disable-next-line:no-implicit-dependencies // tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from 'tapbundle'; import { expect, tap } from '@pushrocks/tapbundle';
import { Timer } from '../ts/index'; import { Timer } from '../ts/index';
@ -15,4 +15,12 @@ tap.test('should start timer', async () => {
await testTimer.completed; await testTimer.completed;
}); });
tap.test('should reset a timer', async () => {
testTimer.reset();
testTimer.start();
testTimer.reset();
testTimer.start();
await testTimer.completed;
});
tap.start(); tap.start();

View File

@ -1,5 +1,5 @@
// tslint:disable-next-line:no-implicit-dependencies // tslint:disable-next-line:no-implicit-dependencies
import { expect, tap } from 'tapbundle'; import { expect, tap } from '@pushrocks/tapbundle';
import * as smarttime from '../ts/index'; import * as smarttime from '../ts/index';
// Test TimeStamp class // Test TimeStamp class

View File

@ -1,8 +1,10 @@
import * as plugins from './smarttime.plugins'; import * as plugins from './smarttime.plugins';
export * from './smarttime.classes.cronmanager';
export * from './smarttime.classes.extendeddate';
export * from './smarttime.classes.hrtmeasurement'; export * from './smarttime.classes.hrtmeasurement';
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 { moment } from './smarttime.plugins'; export { luxon } from './smarttime.plugins';

View File

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

View File

@ -0,0 +1,49 @@
import * as plugins from './smarttime.plugins';
import { CronJob } from './smarttime.classes.cronjob';
import { Timer } from './smarttime.classes.timer';
import { Interval } from './smarttime.classes.interval';
export class CronManager {
public cronInterval = new Interval(1000);
public status: 'started' | 'stopped' = 'stopped';
public cronjobs: CronJob[] = [];
constructor() {
this.cronInterval.addIntervalJob(() => {
for (const cronJob of this.cronjobs) {
cronJob.checkExecution();
}
});
}
public addCronjob(cronIdentifierArg: string, cronFunctionArg: () => any) {
const newCronJob = new CronJob(this, cronIdentifierArg, cronFunctionArg);
this.cronjobs.push(newCronJob);
if (this.status === 'started') {
newCronJob.start();
}
}
/**
* starts the cronjob
*/
public start() {
this.status = 'started';
for (const cron of this.cronjobs) {
cron.start();
}
this.cronInterval.start();
}
/**
* stops all cronjobs
*/
public stop() {
this.status = 'stopped';
for (const cron of this.cronjobs) {
cron.stop();
}
this.cronInterval.stop();
}
}

View File

@ -1 +0,0 @@
import * as plugins from './smarttime.plugins';

View File

@ -0,0 +1,127 @@
import * as plugins from './smarttime.plugins';
export type TAvailableZone = 'Europe/Berlin';
export interface IDateUnits {
year: number;
yearString: string;
month: number;
monthString: string;
monthName: string;
day: number;
dayString: string;
dayOfTheWeek: number;
dayOfTheWeekName: string;
}
export class ExtendedDate extends Date {
// STATIC factories
public static fromMillis(milliSeconds: number) {
return new ExtendedDate(milliSeconds);
}
public static fromDate(dateArg: Date) {
return new ExtendedDate(dateArg.getTime());
}
public static fromEuropeanDate(europeanDate: string) {
const dateArray = /(.*)\.(.*)\.(.*)/.exec(europeanDate);
const luxonDate = plugins.luxon.DateTime.utc(
parseFloat(dateArray[3]), // year
parseFloat(dateArray[2]), // month
parseFloat(dateArray[1]) // day
);
const unixMilli = luxonDate.toMillis();
return new ExtendedDate(unixMilli);
}
/**
* creates an Extended date from a hypedDate like "2018-03-28"
* @param dateString
*/
public static fromHyphedDate(dateString: string) {
// guards
// implementation
const dateMillis = new Date(dateString).getTime();
return new ExtendedDate(dateMillis);
}
/**
* Same as .fromEuropeanDate(), but accepts additional timeArg and zoneArg
*/
public static fromEuropeanDateAndTime(
europeanDateArg: string,
timeArg: string = '12:00:00',
zoneArg: TAvailableZone = 'Europe/Berlin'
) {
// guards
// implementation
const dateArray = /(.*)\.(.*)\.(.*)/.exec(europeanDateArg);
const sliceDate = (dateString: string) => {
return `0${dateString}`.slice(-2);
};
const dateTimeString = `${dateArray[3]}-${sliceDate(dateArray[2])}-${sliceDate(
dateArray[1]
)}T${timeArg}`;
const luxonDate = plugins.luxon.DateTime.fromISO(dateTimeString, {
zone: zoneArg
});
const unixMilli = luxonDate.toMillis();
return new ExtendedDate(unixMilli);
}
// INSTANCE
public timezone: TAvailableZone;
constructor(unixMilli: number) {
super(unixMilli);
}
//
public exportToEuropeanDate() {
const units = this.exportToUnits();
return `${units.dayString}.${units.monthString}.${units.yearString}`;
}
/**
* exports units
*/
public exportToUnits(): IDateUnits {
const monthsArray = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
const daysArray = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];
return {
year: this.getFullYear(),
yearString: `${this.getFullYear()}`,
month: this.getMonth() + 1,
monthString: ("0" + (this.getMonth() + 1)).slice(-2),
monthName: monthsArray[this.getMonth()],
day: this.getDate(),
dayString: ("0" + this.getDate()).slice(-2),
dayOfTheWeek: this.getDay(),
dayOfTheWeekName: daysArray[this.getDay()]
};
}
}

View File

@ -1,11 +1,9 @@
import * as process from 'process';
/** /**
* easy high resolution time measurement * easy high resolution time measurement
*/ */
export class HrtMeasurement { export class HrtMeasurement {
nanoSeconds: number = null; public nanoSeconds: number = null;
milliSeconds: number = null; public milliSeconds: number = null;
private _hrTimeStart = null; private _hrTimeStart = null;
private _hrTimeStopDiff = null; private _hrTimeStopDiff = null;
private _started: boolean = false; private _started: boolean = false;
@ -13,7 +11,7 @@ export class HrtMeasurement {
/** /**
* start the measurement * start the measurement
*/ */
start() { public start() {
this._started = true; this._started = true;
this._hrTimeStart = process.hrtime(); this._hrTimeStart = process.hrtime();
} }
@ -21,7 +19,7 @@ export class HrtMeasurement {
/** /**
* stop the measurement * stop the measurement
*/ */
stop() { public stop() {
if (this._started === false) { if (this._started === false) {
console.log("Hasn't started yet"); console.log("Hasn't started yet");
return; return;
@ -35,7 +33,7 @@ export class HrtMeasurement {
/** /**
* reset the measurement * reset the measurement
*/ */
reset() { public reset() {
this.nanoSeconds = null; this.nanoSeconds = null;
this.milliSeconds = null; this.milliSeconds = null;
this._hrTimeStart = null; this._hrTimeStart = null;

View File

@ -0,0 +1,40 @@
import * as plugins from './smarttime.plugins';
export class Interval {
public status: 'started' | 'stopped' | 'initial' = 'initial';
private statusAuthorization: any = null;
public intervalMilliseconds: number;
public intervalJobs: Array<() => any> = [];
constructor(intervalMillisencondsArg: number) {
this.intervalMilliseconds = intervalMillisencondsArg;
}
public start() {
this.status = 'started';
const statusAuth = new Date();
this.statusAuthorization = statusAuth;
const runInterval = async () => {
while (this.status === 'started' && this.statusAuthorization === statusAuth) {
await plugins.smartdelay.delayFor(this.intervalMilliseconds);
this.executeIntervalJobs();
}
};
runInterval();
}
public stop () {
this.status = 'stopped';
this.statusAuthorization = null;
}
public addIntervalJob(funcArg: () => any) {
this.intervalJobs.push(funcArg);
}
private executeIntervalJobs () {
for (const funcArg of this.intervalJobs) {
funcArg();
}
}
}

View File

@ -39,7 +39,7 @@ export class Timer {
private currentTimeout: NodeJS.Timer; private currentTimeout: NodeJS.Timer;
// a deferred triggeted when Timer has completed // a deferred triggeted when Timer has completed
private completedDeferred = plugins.smartq.defer<void>(); private completedDeferred = plugins.smartpromise.defer<void>();
constructor(timeInMillisecondsArg: number) { constructor(timeInMillisecondsArg: number) {
this.timeInMilliseconds = timeInMillisecondsArg; this.timeInMilliseconds = timeInMillisecondsArg;
@ -61,8 +61,11 @@ export class Timer {
} }
public pause() { public pause() {
clearTimeout(this.currentTimeout); if (this.startedAt) {
this.pausedAt = TimeStamp.fromTimeStamp(this.startedAt); clearTimeout(this.currentTimeout);
this.currentTimeout = null;
this.pausedAt = TimeStamp.fromTimeStamp(this.startedAt);
}
} }
public resume() { public resume() {
@ -70,6 +73,14 @@ export class Timer {
this.currentTimeout = setTimeout(() => { this.currentTimeout = setTimeout(() => {
this.completedDeferred.resolve(); this.completedDeferred.resolve();
}, this.timeLeft); }, this.timeLeft);
} else {
throw new Error('timer has NOT been started before. Please use .start() instead');
} }
} }
public reset() {
this.pause();
this.startedAt = null;
this.pausedAt = null;
}
} }

View File

@ -65,6 +65,11 @@ export class TimeStamp {
} }
} }
/**
* returns a boolean for wether a timestamp is younger
* @param TimeStampArg
* @param tresholdTimeArg
*/
public isYoungerThanOtherTimeStamp(TimeStampArg: TimeStamp, tresholdTimeArg: number = 0) { public isYoungerThanOtherTimeStamp(TimeStampArg: TimeStamp, tresholdTimeArg: number = 0) {
if (this.milliSeconds > TimeStampArg.milliSeconds + tresholdTimeArg) { if (this.milliSeconds > TimeStampArg.milliSeconds + tresholdTimeArg) {
return true; return true;

View File

@ -1,4 +1,11 @@
import * as moment from 'moment'; // @pushrocks scope
import * as smartq from 'smartq'; import * as smartdelay from '@pushrocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise';
export { moment, smartq }; export { smartdelay, smartpromise };
// third parties
import cronParser from 'cron-parser';
import * as luxon from 'luxon';
export { cronParser, luxon };

View File

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