官术网_书友最值得收藏!

The timer operator

The timer operator creates an observable that emits an item after an absolute or relative time has elapsed. After this first emission, the observable emits items periodically if a period value has been provided. The following figure shows the marble diagram of the timer operator without a period:

Figure 4.7: The timer operator as a single shot

The following figure shows the marble diagram of the timer operator with a period:

Figure 4.8: The timer operator with a periodic item emission

The prototype of this operator is as follows:

Observable.timer(duetime, period=None, scheduler=None)

The duetime parameter can be an absolute or relative value. Absolute values are provided as timedate objects. Relative values are provided as integers in units of milliseconds.

The period parameter is optional. When it is omitted, the observable emits a single item, the 0 number, and completes. Otherwise, the observable emits increasing numbers at the period provided. The period parameter is an integer that represents milliseconds.

The following is an example of a single shot timer observable:

import datetime

print("starting at {}".format(datetime.datetime.now()))
one_shot = Observable.timer(1000)
one_shot.subscribe(
on_next=lambda i: print("tick {} at {}".format(
i, datetime.datetime.now())),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The preceding code will provide the following results:

starting at 2018-06-21 23:25:08.451966
tick 0 at 2018-06-21 23:25:09.456590
completed

As expected, the item was received one second after the program started. The following example (with a period) never ends unless it is interrupted:

import datetime

print("starting at {}".format(datetime.datetime.now()))
tick = Observable.timer(1000, period=500)
tick.subscribe(
on_next=lambda i: print("tick {} at {}".format(
i, datetime.datetime.now())),
on_error=lambda e: print("error: {}".format(e)),
on_completed=lambda: print("completed")
)

The output is as follows:

starting at 2018-06-21 23:38:26.375393
tick 0 at 2018-06-21 23:38:27.379811 tick 1 at 2018-06-21 23:38:27.878076 tick 2 at 2018-06-21 23:38:28.379091 tick 3 at 2018-06-21 23:38:28.877043 tick 4 at 2018-06-21 23:38:29.381027
...

The first item is received after one second, but the other ones are received every 500 milliseconds. Note that the value of the item increases at each emission.

主站蜘蛛池模板: 米泉市| 苏尼特左旗| 宜兰市| 武陟县| 大城县| 桐乡市| 灵台县| 和林格尔县| 亚东县| 南城县| 壤塘县| 赤水市| 太保市| 河间市| 甘谷县| 崇仁县| 咸丰县| 南溪县| 芦溪县| 奉化市| 抚顺市| 遂平县| 罗甸县| 上杭县| 靖西县| 全南县| 托克逊县| 兴安盟| 千阳县| 嘉善县| 茶陵县| 铁岭市| 榆中县| 梁山县| 县级市| 沈阳市| 陇川县| 承德县| 三明市| 黄浦区| 庆阳市|