2023-03-01 09:39:41 -06:00
|
|
|
/**
|
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
2024-05-31 11:29:24 -07:00
|
|
|
* SPDX-License-Identifier: BUSL-1.1
|
2023-03-01 09:39:41 -06:00
|
|
|
*/
|
|
|
|
|
|
2022-04-28 16:23:44 -04:00
|
|
|
import Service from '@ember/service';
|
|
|
|
|
import { tracked } from '@glimmer/tracking';
|
|
|
|
|
import { getOwner } from '@ember/application';
|
2025-03-06 12:20:48 -08:00
|
|
|
import { task, timeout } from 'ember-concurrency';
|
2022-04-28 16:23:44 -04:00
|
|
|
|
|
|
|
|
export default class ClockTickService extends Service {
|
|
|
|
|
// =attributes
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The current datetime. This is updated once every `interval` while the
|
|
|
|
|
* service is running (1s by default).
|
|
|
|
|
* @type {number}
|
|
|
|
|
*/
|
|
|
|
|
@tracked now = Date.now();
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The frequency to update `now`, in milliseconds.
|
|
|
|
|
* @type {number}
|
|
|
|
|
*/
|
|
|
|
|
frequency = 1000;
|
|
|
|
|
|
|
|
|
|
/**
|
2025-03-06 12:20:48 -08:00
|
|
|
* Updates the value of `now` every `frequency` milliseconds.
|
2022-04-28 16:23:44 -04:00
|
|
|
*/
|
2025-03-06 12:20:48 -08:00
|
|
|
_tick = task(async () => {
|
|
|
|
|
// eslint-disable-next-line no-constant-condition
|
|
|
|
|
while (true) {
|
|
|
|
|
await timeout(this.frequency);
|
|
|
|
|
this.now = Date.now();
|
|
|
|
|
}
|
|
|
|
|
});
|
2022-04-28 16:23:44 -04:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* This service is enabled only in non-test environments.
|
|
|
|
|
* @type {boolean}
|
|
|
|
|
*/
|
|
|
|
|
get enabled() {
|
|
|
|
|
const config = getOwner(this).resolveRegistration('config:environment');
|
|
|
|
|
return config.environment !== 'test';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// =methods
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Starts the timer, if enabled.
|
|
|
|
|
*/
|
|
|
|
|
constructor() {
|
|
|
|
|
super(...arguments);
|
2025-03-06 12:20:48 -08:00
|
|
|
if (this.enabled) this._tick.perform();
|
2022-04-28 16:23:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Stops the timer.
|
|
|
|
|
*/
|
|
|
|
|
willDestroy() {
|
|
|
|
|
super.willDestroy(...arguments);
|
2025-03-06 12:20:48 -08:00
|
|
|
this._tick.cancelAll();
|
2022-04-28 16:23:44 -04:00
|
|
|
}
|
|
|
|
|
}
|