Avoid generating a Context() object every second (#38085)

Every second we were calling the getrandom() syscall to generate a uuid4
for a context that will never be looked:

 * In most setups there are no more time_changed listeners

 * The ones that do exist never care about context

 * time_changed events are never saved in the database
This commit is contained in:
J. Nick Koston 2020-07-22 18:52:10 -10:00 committed by GitHub
parent 2b3f22c871
commit d7811a4adf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 5 deletions

View File

@ -1539,6 +1539,7 @@ class Config:
def _async_create_timer(hass: HomeAssistant) -> None:
"""Create a timer that will start on HOMEASSISTANT_START."""
handle = None
timer_context = Context()
def schedule_tick(now: datetime.datetime) -> None:
"""Schedule a timer tick when the next second rolls around."""
@ -1553,12 +1554,14 @@ def _async_create_timer(hass: HomeAssistant) -> None:
"""Fire next time event."""
now = dt_util.utcnow()
hass.bus.async_fire(EVENT_TIME_CHANGED, {ATTR_NOW: now})
hass.bus.async_fire(EVENT_TIME_CHANGED, {ATTR_NOW: now}, context=timer_context)
# If we are more than a second late, a tick was missed
late = monotonic() - target
if late > 1:
hass.bus.async_fire(EVENT_TIMER_OUT_OF_SYNC, {ATTR_SECONDS: late})
hass.bus.async_fire(
EVENT_TIMER_OUT_OF_SYNC, {ATTR_SECONDS: late}, context=timer_context
)
schedule_tick(now)

View File

@ -1090,9 +1090,20 @@ def test_timer_out_of_sync(mock_monotonic, loop):
):
callback(target)
event_type, event_data = hass.bus.async_fire.mock_calls[1][1]
assert event_type == EVENT_TIMER_OUT_OF_SYNC
assert abs(event_data[ATTR_SECONDS] - 2.433333) < 0.001
_, event_0_args, event_0_kwargs = hass.bus.async_fire.mock_calls[0]
event_context_0 = event_0_kwargs["context"]
event_type_0, _ = event_0_args
assert event_type_0 == EVENT_TIME_CHANGED
_, event_1_args, event_1_kwargs = hass.bus.async_fire.mock_calls[1]
event_type_1, event_data_1 = event_1_args
event_context_1 = event_1_kwargs["context"]
assert event_type_1 == EVENT_TIMER_OUT_OF_SYNC
assert abs(event_data_1[ATTR_SECONDS] - 2.433333) < 0.001
assert event_context_0 == event_context_1
assert len(funcs) == 2
fire_time_event, _ = funcs