2019-12-08 02:28:57 +08:00
|
|
|
import {EventEmitter, Injectable} from '@angular/core';
|
2019-07-28 04:56:12 +08:00
|
|
|
import {BehaviorSubject} from 'rxjs';
|
|
|
|
import {TaskProgressDTO} from '../../../../common/entities/settings/TaskProgressDTO';
|
|
|
|
import {NetworkService} from '../../model/network/network.service';
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ScheduledTasksService {
|
|
|
|
|
|
|
|
|
|
|
|
public progress: BehaviorSubject<{ [key: string]: TaskProgressDTO }>;
|
2019-12-08 02:28:57 +08:00
|
|
|
public onTaskFinish: EventEmitter<string> = new EventEmitter<string>();
|
2019-07-28 04:56:12 +08:00
|
|
|
timer: number = null;
|
|
|
|
private subscribers = 0;
|
|
|
|
|
|
|
|
constructor(private _networkService: NetworkService) {
|
|
|
|
this.progress = new BehaviorSubject({});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
subscribeToProgress(): void {
|
|
|
|
this.incSubscribers();
|
|
|
|
}
|
|
|
|
|
|
|
|
unsubscribeFromProgress(): void {
|
|
|
|
this.decSubscribers();
|
|
|
|
}
|
|
|
|
|
|
|
|
public forceUpdate() {
|
|
|
|
return this.getProgress();
|
|
|
|
}
|
|
|
|
|
2019-12-08 02:28:57 +08:00
|
|
|
public async start(id: string, config?: any): Promise<void> {
|
|
|
|
await this._networkService.postJson('/admin/tasks/scheduled/' + id + '/start', {config: config});
|
|
|
|
this.forceUpdate();
|
2019-07-28 04:56:12 +08:00
|
|
|
}
|
|
|
|
|
2019-12-08 02:28:57 +08:00
|
|
|
public async stop(id: string): Promise<void> {
|
|
|
|
await this._networkService.postJson('/admin/tasks/scheduled/' + id + '/stop');
|
|
|
|
this.forceUpdate();
|
2019-07-28 04:56:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
protected async getProgress() {
|
2019-12-08 02:28:57 +08:00
|
|
|
const prevPrg = this.progress.value;
|
|
|
|
this.progress.next(await this._networkService.getJson<{ [key: string]: TaskProgressDTO }>('/admin/tasks/scheduled/progress'));
|
|
|
|
for (const prg in prevPrg) {
|
|
|
|
if (!this.progress.value.hasOwnProperty(prg)) {
|
|
|
|
this.onTaskFinish.emit(prg);
|
|
|
|
}
|
|
|
|
}
|
2019-07-28 04:56:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
protected getProgressPeriodically() {
|
|
|
|
if (this.timer != null || this.subscribers === 0) {
|
|
|
|
return;
|
|
|
|
}
|
2019-08-20 18:54:45 +08:00
|
|
|
let repeatTime = 5000;
|
|
|
|
if (Object.values(this.progress.value).length === 0) {
|
|
|
|
repeatTime = 10000;
|
|
|
|
}
|
2019-07-28 04:56:12 +08:00
|
|
|
this.timer = window.setTimeout(async () => {
|
|
|
|
await this.getProgress();
|
|
|
|
this.timer = null;
|
|
|
|
this.getProgressPeriodically();
|
2019-08-20 18:54:45 +08:00
|
|
|
}, repeatTime);
|
2019-07-28 04:56:12 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private incSubscribers() {
|
|
|
|
this.subscribers++;
|
|
|
|
this.getProgressPeriodically();
|
|
|
|
}
|
|
|
|
|
|
|
|
private decSubscribers() {
|
|
|
|
this.subscribers--;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|