[英]How to make requests using rxjs at the certain time?
I need to make request three times a day at a certain time (8 AM, 12 AM, 4 PM).我需要每天在特定时间(上午 8 点、中午 12 点、下午 4 点)提出三次请求。 What is the best way to implement this?实现这一点的最佳方法是什么?
This feels a bit like a strange requirement for a JS task and I think you should rather look into making a Cron task for that.这感觉有点像对 JS 任务的奇怪要求,我认为您应该考虑为此创建一个 Cron 任务。 But for the sake of example, here's how you can do it:但为了举例,您可以这样做:
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));
Live demo: https://stackblitz.com/edit/rxjs-sxxe41现场演示: https : //stackblitz.com/edit/rxjs-sxxe41
PS: I've assumed that the update doesn't need to be triggered as soon as the new minute starts. PS:我假设不需要在新一分钟开始时立即触发更新。 If that's the case, then timer should tick every second and you should use distinctUntilChanged on the current hour/minutes to wait until they're differents.如果是这种情况,那么计时器应该每秒打勾一次,您应该在当前小时/分钟上使用 distinctUntilChanged 以等待它们不同。
You should look into asyncScheduler from RxJS which uses setInterval for time based operations.您应该查看 RxJS 中的 asyncScheduler,它使用 setInterval 进行基于时间的操作。
Refer to this link: https://rxjs-dev.firebaseapp.com/guide/scheduler请参阅此链接: https : //rxjs-dev.firebaseapp.com/guide/scheduler
Ideally cron jobs are best on the server side to deal with functions need executing at different times, might be worth looking in that as well.理想情况下,cron 作业最好在服务器端处理需要在不同时间执行的功能,可能也值得一看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.