Colab long-running cell: graceful shutdown on kernel interrupt and idle timeout
0 reputation · 22 Apr 2022, 13:38 UTC
Google Colab disconnects idle sessions after roughly 90 minutes, and the only way to stop a running cell is the Stop button (kernel interrupt), which abruptly terminates code with no guaranteed cleanup. I want to handle cancellation gracefully in a long-running training cell.
The interrupt raises KeyboardInterrupt in the cell, but I am unsure how to structure the code so that cleanup — like closing file handles, checkpointing model state, and releasing GPU memory — runs reliably before the kernel stops. I also do not know whether the interrupt timing interacts with the idle disconnect timer, or whether autosave can be relied upon to preserve enough state to resume after a forced disconnect.
Is there a documented pattern (e.g., try/finally or context managers) that guarantees cleanup on interrupt? Can I configure or extend the idle timeout, or is the 90-minute boundary fixed across free and paid tiers? How do I verify that autosave has captured the notebook state before the session ends?