- Hands-On Reactive Programming with Python
- Romain Picard
- 326字
- 2021-06-24 18:25:24
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:
The following figure shows the marble diagram of the timer operator with a period:
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:
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:
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.
- 電腦組裝與系統(tǒng)安裝
- 網(wǎng)絡(luò)操作系統(tǒng):Windows Server 2003管理與應(yīng)用
- Ganglia系統(tǒng)監(jiān)控
- 嵌入式操作系統(tǒng)(Linux篇)(微課版)
- Instant Optimizing Embedded Systems using Busybox
- RESS Essentials
- Moodle 3.x Teaching Techniques(Third Edition)
- macOS效率手冊
- Windows Server 2012網(wǎng)絡(luò)操作系統(tǒng)項目教程(第4版)
- iOS 8開發(fā)指南
- Kali Linux高級滲透測試
- Windows 7實戰(zhàn)從入門到精通
- OpenHarmony開發(fā)與實踐:基于紅莓RK2206開發(fā)板
- 再也不踩坑的kubernetes實戰(zhàn)指南
- 15分鐘!畫出我的漫畫角色:賣萌篇