How can I notify specific users in a Python Telegram bot when a separate event occurs?

I have developed a script that constantly monitors my email inbox and posts updates at regular intervals using an endless loop. Now, I intend to implement the same behavior within my Telegram bot. However, when I call the bot’s polling function, it seems to override my continuous loop, or vice versa. How can I ensure that my persistent loop runs concurrently with the bot’s other functionalities without interruption?

Below is an alternative example:

import time
import threading
from telebot import TeleBot

# Function that simulates email monitoring and user notification

def process_emails():
    print('Checking for new messages...')
    # Insert logic to process emails and notify users
    time.sleep(5)

# Create an instance of the bot
my_bot = TeleBot('YOUR_TOKEN_HERE')

# Infinite loop running concurrently

def run_continuously():
    while True:
        process_emails()

# Start the continuous process in a separate thread
continuous_thread = threading.Thread(target=run_continuously)
continuous_thread.start()

# Begin bot polling concurrently
my_bot.polling()

I ran into a similar challenge while developing a more comprehensive monitoring solution. Initially, I tried threading, but I ended up with race conditions and lots of debugging to synchronize shared state between the email checking process and the Telegram bot events. Eventually, I shifted to using asynchronous programming with asyncio and aiogram. This allowed me to run both your continuous email monitoring and the bot polling in separate coroutines, which reduced complexity and improved reliability. Consolidating error handling and timeouts into the async loop also helped keep things running smoothly.