The Real Challenge of Turning Off Lights on a Schedule in Home Assistant: Why Might a Task Run Twice After a Restart?
A runnable SQLite and simulated-lamp experiment explores restart recovery, duplicate actions, fresh observations and stale task completions, with scripts and recorded results.
Updated
The previous article discussed how a Home Assistant restart interrupts for conditions and delays already in progress. The most natural fix is to save the deadline and check for overdue tasks after startup.
But a deadline only answers “when should this happen?” There is a harder question: What should the system do after an action succeeds but before it manages to record completion, if it then restarts?
Retrying may execute the action twice. Not retrying may leave a task undone when it was never executed. Writing the time to a helper does not make this dilemma disappear.
This article uses SQLite and a simulated lamp for fault-injection experiments, then discusses the tradeoffs for ordinary home lighting. The script was run, but this was not a Home Assistant integration test, and no devices in your home were controlled. The state machine presented here is a design reference, not complete YAML you can paste directly into Home Assistant.
First, Distinguish Two Rules That Look Alike
“Turn off the light after ten minutes” can express two different requirements:
| Rule | Fact that matters | Gap caused by downtime |
|---|---|---|
| Turn off the light after the room has been continuously unoccupied for ten minutes | The room was unoccupied for the entire interval | The system may not know whether someone entered during downtime |
| A user starts a ten-minute countdown; attempt to turn off the light when it expires | The deadline and the conditions at execution time | The deadline may be missed, and the execution result may go unrecorded |
These rules are not interchangeable.
For the first rule, restoring an old timestamp cannot prove that the room remained unoccupied during downtime. Without an independent, reliable sensor history, a conservative policy is to observe the room again for a period of time.
The experiments here address the second rule: a user explicitly creates a scheduled task to turn off a light, and when it is due, the system attempts to turn off an ordinary test lamp only after obtaining a sufficiently fresh observation that the room is unoccupied. The experiments do not claim to reconstruct continuous occupancy during downtime.
Why a Single Date-and-Time Helper Is Not Enough
Home Assistant’s input_datetime can store a date and time. According to its official documentation, it starts from a valid initial value if one is set; otherwise, it restores its state from before shutdown.[1]
That makes it suitable for recording a deadline. But “the deadline was ten o’clock last night” does not tell you whether the task is still valid. It may have been completed, canceled by the user, or superseded by a later countdown.
At a minimum, the system therefore needs to represent three things: task identity, deadline, and task state. For example:
id=42
due=a specific deadline
state=pending
id distinguishes old tasks from new ones; due determines when an attempt is allowed; and state distinguishes pending, completed, and canceled tasks.
Several Home Assistant helpers can represent similar information, but updates to multiple helpers cannot simply be treated as one database transaction. If the design strictly depends on those updates succeeding or failing together, it needs a component with the appropriate persistence and transactional capabilities, and its recovery behavior must be verified. This article uses SQLite to study the issue separately from UI configuration; it does not suggest modifying Home Assistant’s own database directly.
An Interruption Window You Cannot Ignore
Suppose the deadline has passed and the execution flow is:
Read the pending task
Check the current conditions
Send the turn-off action
Write the task as done
If the program is interrupted after step three but before step four, the light may already be off while the task on disk remains pending. After a restart, that record may look exactly the same as it would if the program had been interrupted before sending the action at all.
Reversing the order does not solve the problem: if the system writes done before turning off the light and is interrupted between those steps, the task is recorded as complete while the light remains on.
| Accounting order | Interruption window | Recovery risk |
|---|---|---|
| Mark complete, then execute | After the completion record is written, before the action | Missed execution |
| Execute, then mark complete | After the action, before the completion record is written | Duplicate execution |
A local SQLite transaction protects only the local records. It cannot include the physical action of a remote lamp in that same transaction. Stronger guarantees require mechanisms such as request deduplication or queryable operation results at the execution endpoint, with a protocol coordinated between the two sides. A flag in an automation cannot provide those guarantees by itself.
Experiment: The Same Two Attempts Produce Opposite Results With off and toggle
We set up a simulated lamp that starts on, create a task with a deadline of 600, and attempt execution at simulated time 700.
The fault is injected after the lamp receives the action but before the task is written as complete. The script then closes and reopens the database, simulating the persistent state seen by the next run. The time values are injected integers, not measured seconds; the operating system is not actually powered off.
After recovery, the task is still pending, so execution is attempted again.
Results from this run:
crash_after_action_off calls=2 lamp_on=false
crash_after_action_toggle calls=2 lamp_on=true
Turning the simulated lamp off twice leaves it off. Toggling it twice turns it back on.
Therefore, tasks that permit retries after recovery should favor actions with an explicit target state, such as “turn off,” over actions that “flip the current state.” That is the practical value of idempotence in this small scenario.
It is not, however, a license to retry indefinitely. If a user manually turns the light on between two off commands, the second command may still contradict their intent. Real devices may also produce additional actions or events in response to repeated commands. We verified idempotence only for the simulated lamp’s Boolean state, not for a device’s electrical behavior or every automation side effect.
Why “Unoccupied” After Recovery Might Be an Old Value
If the sensor state reads off at startup, another question matters: was this a new observation received after startup, or an old state that was restored?
The experiment requires an observation to meet three conditions:
It explicitly reports unoccupied
Its receipt time is no earlier than this startup
It is no older than the model’s freshness window at the time of the check
The script uses 30 simulated time units as the window solely to test the boundary. It is not a recommendation to use 30 seconds for every real device. A real threshold should depend on the device’s reporting interval and the consequences of the action.
The experiment supplies an old pre-startup off, unknown, on, and an off outside the window; none causes a turn-off call. Only a newly received off within the window permits the action.
This also exposes a practical integration challenge: some devices report only when their state changes, some integrations restore cached values, and some read operations do not necessarily contact the device directly. Do not assume that an arbitrary timestamp on an entity proves “the hardware just reconfirmed that the room is unoccupied.” Check the data source for the specific device being integrated. If a reliable fresh observation is unavailable, keep the task waiting or choose manual handling.
Neither unknown nor unavailable becomes “unoccupied” merely because it is “not on.”
An Old Task’s Acknowledgment Must Not Clear a New Task
A user may set a later turn-off time before the first countdown has finished. If an old callback then sets a global pending flag to false, it could inadvertently clear the new task.
The experiment assigns different IDs to tasks and uses a conditional update:
UPDATE job
SET state = 'done'
WHERE id = ? AND state = 'pending';
When a new task is created, the old pending task is canceled and the new one is inserted in the same SQLite transaction. A completion notification for the old task carries only its old ID, so it cannot mark the new task complete.
In the experiment, the old task has ID 1 and deadline 600; the new task has ID 2 and deadline 900. After the old task’s completion callback arrives, there is no executable task at time 700, and task 2 is still available at time 901.
But task IDs protect only the accounting. They cannot recall an old command already sent to a device. If an old request is still in transit when the new task is created, and the device executes it later, it may still contradict the user’s new intent. A real system needs further consideration of serialized execution, cancellation semantics, and version checks at the execution endpoint. The single-executor model here does not solve concurrent commands in the network.
What Checks Are Needed When Integrating With Home Assistant?
Besides the normal time trigger, checks should at least be considered after startup and after key entities recover. A low-frequency fallback check can also be scheduled to handle missed wake-ups. Every check must read the task state; being triggered does not, by itself, mean the action should execute.
The official Timer documentation explicitly states that enabling restore can restore active or paused timers, but a timer that expires during downtime will not emit timer.finished on startup.[2] The state-trigger documentation also explicitly states that for resets when Home Assistant restarts or automations are reloaded.[3]
These facts establish the need for a recovery check. They do not make this rule inherently safe:
Current time is past an old deadline → turn off the light unconditionally
A recovery check should also establish that the task is still valid, the target device exists, current conditions permit the action, the state evidence is sufficiently fresh, and there is no explicit manual override.
Boundaries for stopping automatic attempts should also be defined for cases such as an untrustworthy clock, a device that remains unavailable, or repeated failures. This model does not implement a maximum retry count, backoff, or alerts. Those must be added before real integration; commands must not be sent indefinitely.
Which Conclusions Can You Reproduce?
Accompanying file: deadline_lab.py. It uses the Python 3 standard library. Its temporary SQLite database is deleted after the run. It needs no Home Assistant token and does not access real devices.
python deadline_lab.py
Assertions passed for all four scenario groups in this run, and the results were saved as deadline_results.json:
| Scenario | What was verified |
|---|---|
| Close and reopen the database, then check the conditions | The pending task remains; old, unknown, occupied, and stale observations are blocked; a valid fresh observation triggers one action |
Interrupt after the action but before writing completion, then retry off |
The action is called twice, and the simulated lamp ends up off |
Interrupt at the same point, then retry toggle |
The action is called twice, and the simulated lamp ends up on |
| A new task replaces an old task, then the old acknowledgment arrives | The old acknowledgment does not complete the new task |
These four results do not prove durability across a power failure, that Home Assistant helpers have SQLite transaction semantics, or that concurrent execution by multiple executors is correct. The experiment deliberately retains the gap where an action has executed but its state has not been committed, to show why local accounting alone cannot promise exactly-once execution.
For an ordinary light at home, it is often acceptable to confirm current conditions after recovery, send an explicit turn-off command again if needed, and provide a way to cancel. The same tradeoff may be entirely unacceptable for a charge, an unlock operation, or a one-time dispense.
When designing a scheduled task, the question that must be answered is: at the moment the system has forgotten the action’s result, which is less acceptable to you, missing the action or repeating it? Only when that choice is explicit does recovery logic have a verifiable goal.
References
Checked on: 2026-11-14. The official site showed Home Assistant 2026.11.1; that version was not installed for the experiment.
- Input Datetime: Restore state.
- Timer: Restoration and the limitation on expiry during downtime.
- State changed: Restart behavior of
for. - Experiment script and raw results: the software model run for this article and its output.
This article was researched, written, and verified with AI assistance. Simulated time, a simulated lamp, and injected interruptions are not equivalent to testing in a real home environment.
Download the complete experiment package (script, results, and run log)
AI-generated concept illustration, not a screenshot or photograph of this experiment.
Discussion
Share a question or your experience. Comments appear after moderation. Your email is never displayed publicly. Comment privacy
Loading comments…