Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent time pattern reschedule if cancelled during job execution #117879

Merged
merged 3 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion homeassistant/helpers/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -1776,14 +1776,14 @@ def _pattern_time_change_listener(self, _: datetime) -> None:
# time when the timer was scheduled
utc_now = time_tracker_utcnow()
localized_now = dt_util.as_local(utc_now) if self.local else utc_now
hass.async_run_hass_job(self.job, localized_now, background=True)
if TYPE_CHECKING:
assert self._pattern_time_change_listener_job is not None
self._cancel_callback = async_track_point_in_utc_time(
hass,
self._pattern_time_change_listener_job,
self._calculate_next(utc_now + timedelta(seconds=1)),
)
hass.async_run_hass_job(self.job, localized_now, background=True)

@callback
def async_cancel(self) -> None:
Expand Down
34 changes: 34 additions & 0 deletions tests/helpers/test_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -4589,6 +4589,40 @@ def run_callback(local_time):
assert "US/Hawaii" in str(times[0].tzinfo)


async def test_async_track_point_in_time_cancel_in_job(
hass: HomeAssistant, freezer: FrozenDateTimeFactory
) -> None:
"""Test cancel of async track point in time during job execution."""

now = dt_util.utcnow()
times = []

time_that_will_not_match_right_away = datetime(
now.year + 1, 5, 24, 11, 59, 55, tzinfo=dt_util.UTC
)
freezer.move_to(time_that_will_not_match_right_away)

@callback
def action(x: datetime):
nonlocal times
times.append(x)
unsub()

unsub = async_track_utc_time_change(hass, action, minute=0, second="*")

async_fire_time_changed(
hass, datetime(now.year + 1, 5, 24, 12, 0, 0, 999999, tzinfo=dt_util.UTC)
)
await hass.async_block_till_done()
assert len(times) == 1

async_fire_time_changed(
hass, datetime(now.year + 1, 5, 24, 13, 0, 0, 999999, tzinfo=dt_util.UTC)
)
await hass.async_block_till_done()
assert len(times) == 1


async def test_async_track_entity_registry_updated_event(hass: HomeAssistant) -> None:
"""Test tracking entity registry updates for an entity_id."""

Expand Down