Skip to content

Commit 3794526

Browse files
committed
on_close
1 parent 2ef9156 commit 3794526

File tree

3 files changed

+25
-3
lines changed

3 files changed

+25
-3
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,19 @@ if __name__ == "__main__":
115115
probe.start()
116116
```
117117

118+
## On CLose
119+
120+
Using the `set_on_close()` method, it is possible to configure a method which will be called before the probe is stopped.
121+
This can be useful in case you want to nicely close some connections.
122+
123+
```python
124+
async def custom_on_close():
125+
...
126+
127+
probe = Probe("myProbe", '3.0.0', {})
128+
probe.set_on_close(custom_on_close)
129+
```
130+
118131
## ASCII item names
119132

120133
InfraSonar requires each item to have a unique _name_ property. The value for _name_ must be a _string_ with ASCII compatible character.

libprobe/probe.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ def __init__(
136136
self._checks: Dict[Tuple[int, int], asyncio.Future] = {}
137137
self._dry_run: Optional[Tuple[Asset, dict]] = \
138138
None if dry_run is None else self._load_dry_run_assst(dry_run)
139+
self._on_close: Callable[[], Awaitable[None]] | None = None
139140

140141
if not os.path.exists(config_path):
141142
try:
@@ -202,11 +203,17 @@ def is_connected(self) -> bool:
202203
def is_connecting(self) -> bool:
203204
return self._connecting
204205

206+
def set_on_close(self, on_close: Callable[[], Awaitable[None]]):
207+
self._on_close = on_close
208+
205209
def _stop(self, signame, *args):
206210
logging.warning(
207211
f'signal \'{signame}\' received, stop {self.name} probe')
208-
for task in asyncio.all_tasks():
209-
task.cancel()
212+
if self._on_close is not None and self.loop is not None:
213+
self.loop.run_until_complete(self._on_close())
214+
else:
215+
for task in asyncio.all_tasks():
216+
task.cancel()
210217

211218
async def _start(self):
212219
initial_step = 2
@@ -335,6 +342,8 @@ async def _do_dry_run(self):
335342
output = json.dumps(response, indent=2)
336343
print(output)
337344
print('', file=sys.stderr)
345+
if self._on_close is not None:
346+
await self._on_close()
338347

339348
async def _connect(self):
340349
assert self.loop is not None

libprobe/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '1.0.1'
1+
__version__ = '1.0.2'

0 commit comments

Comments
 (0)