Created
June 7, 2025 23:19
-
-
Save derailed-dash/8335e124789f1719e904aea180474802 to your computer and use it in GitHub Desktop.
Keepalive background thread for a Jupyter notebook
This file contains hidden or 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
import time | |
import datetime | |
import threading | |
# Global flag to control the thread's execution | |
keep_alive_thread_running = False | |
keep_alive_thread = None # To store the thread object | |
def keep_colab_active_target(): | |
global keep_alive_thread_running | |
print(f"[{datetime.datetime.now()}] Colab Keep-Alive Thread Started.") | |
while keep_alive_thread_running: | |
print(f"[{datetime.datetime.now()}] Keeping Colab active...") | |
# A small sleep is usually sufficient to register activity | |
# and not consume too many resources. | |
time.sleep(60 * 5) # Sleep for 5 minutes | |
print(f"[{datetime.datetime.now()}] Colab Keep-Alive Thread Stopped.") | |
def start_keep_alive(): | |
global keep_alive_thread_running, keep_alive_thread | |
if not keep_alive_thread_running: | |
keep_alive_thread_running = True | |
keep_alive_thread = threading.Thread(target=keep_colab_active_target) | |
keep_alive_thread.daemon = True # Allows the main program to exit even if thread is running | |
keep_alive_thread.start() | |
print("Colab Keep-Alive thread initiated. It will run in the background.") | |
else: | |
print("Colab Keep-Alive thread is already running.") | |
def stop_keep_alive(): | |
global keep_alive_thread_running, keep_alive_thread | |
if keep_alive_thread_running: | |
keep_alive_thread_running = False | |
if keep_alive_thread and keep_alive_thread.is_alive(): | |
# Give the thread a moment to finish its current sleep cycle | |
# In a real application, you might use a more sophisticated stop mechanism | |
# involving events or queues. For simple keep-alive, this is often fine. | |
print("Attempting to stop Colab Keep-Alive thread. Please wait for its current cycle to finish...") | |
# We don't join directly here as it would block the cell. | |
# The thread will naturally exit on its next loop iteration. | |
else: | |
print("Colab Keep-Alive thread is not running.") | |
# --- How to use --- | |
# Run this cell once to define the functions. | |
# To start the keep-alive: | |
# Call this in a separate cell, or at the beginning of your notebook execution. | |
start_keep_alive() | |
# To stop the keep-alive (e.g., when you're done or before closing Colab): | |
# Call this in a separate cell. | |
# stop_keep_alive() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment