-
Notifications
You must be signed in to change notification settings - Fork 100
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
adding code to run a script in async with the keyboard ctrl-c handler…
… as a base to help create scripts without having to repeat boilerplate code
- Loading branch information
1 parent
a01fdfa
commit 7f3cb56
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import BAC0 | ||
import asyncio | ||
from signal import SIGINT, SIGTERM, signal | ||
import click | ||
from BAC0.tools.jci_tec_points_list import tec_short_point_list | ||
from BAC0.tasks.RecurringTask import RecurringTask | ||
import os | ||
|
||
def run(main_task, bacnet): | ||
global loop | ||
|
||
def handler(sig, sig2): | ||
bacnet._log.info(f"Got signal: {sig!s}, shutting down.") | ||
bacnet.disconnect() | ||
loop.stop() | ||
|
||
try: | ||
loop = asyncio.get_running_loop() #we also could have chosen get_event_loop(), and if we did we would not have needed to set_event_loop() and create a new event loop | ||
except RuntimeError: | ||
loop = asyncio.new_event_loop() | ||
asyncio.set_event_loop(loop) | ||
# for sig in (SIGINT, SIGTERM): | ||
# loop.add_signal_handler(sig, handler) | ||
signal(SIGINT, handler) | ||
signal(SIGTERM, handler) | ||
|
||
loop.create_task(main_task()) | ||
loop.run_forever() | ||
tasks = asyncio.all_tasks(loop=loop) | ||
for t in tasks: | ||
t.cancel() | ||
group = asyncio.gather(*tasks, return_exceptions=True) | ||
loop.run_until_complete(group) | ||
loop.close() |