【发布时间】:2020-01-23 11:17:22
【问题描述】:
我需要每天在特定时间(上午 8 点、上午 12 点、下午 4 点)提出 3 次请求。 实现这一点的最佳方法是什么?
【问题讨论】:
标签: javascript angular rxjs rxjs6
我需要每天在特定时间(上午 8 点、上午 12 点、下午 4 点)提出 3 次请求。 实现这一点的最佳方法是什么?
【问题讨论】:
标签: javascript angular rxjs rxjs6
这感觉有点像 JS 任务的奇怪要求,我认为您应该考虑为此创建一个 Cron 任务。但是为了举例,你可以这样做:
import { of, Observable, timer, EMPTY } from "rxjs";
import { map, filter, timestamp, switchMap } from "rxjs/operators";
type Hour = number;
type Minutes = number;
const atTimes = (times: [Hour, Minutes][]): Observable<[Hour, Minutes]> =>
timer(0, 1000 * 60).pipe(
switchMap(() => {
const date: Date = new Date();
const [currentHour, currentMinutes] = [
date.getHours(),
date.getMinutes()
];
const time = times.find(
([hour, minutes]) => hour === currentHour && minutes === currentMinutes
);
if (!time) {
return EMPTY;
}
return of(time);
})
);
atTimes([[11,48]]).subscribe(x => console.log(x));
现场演示:https://stackblitz.com/edit/rxjs-sxxe41
PS:我假设不需要在新一分钟开始时立即触发更新。如果是这种情况,那么计时器应该每秒滴答一次,您应该在当前小时/分钟上使用 distinctUntilChanged 等待它们不同。
【讨论】:
您应该查看 RxJS 中的 asyncScheduler,它使用 setInterval 进行基于时间的操作。
参考此链接:https://rxjs-dev.firebaseapp.com/guide/scheduler
理想情况下,cron 作业最好在服务器端处理需要在不同时间执行的功能,这可能也值得研究。
【讨论】: