Search code examples
pythonherokucrontelegram-bot

How can I prevent my bot to fall asleep/idiling on Heroku!?, Cronjob is not executing after bot starts polling?


hope yall doing well. I have a telegram bot that I deployed on Heroku, but the bot fall asleep after 20-30 minutes, because I'm using Heroku's free dyno, I tried to prevent this by creating a cronjob which only prints something in the console to keep the bot awake.

As you can see below I have 2 functions, start_polling & cronjob but since I execute the start_polling first, cronjob won't execute

Is there any trick that I can use here to prevent my bot fall asleep!?

import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'telega.settings')
django.setup()

from main.bot import bot
from crontab import CronTab
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

def cronjob():
    """ Main cron job to prevent bot fall asleep. """
    print("Cron job is running, bot wont fall asleep")
    print("Tick! The time is: %s" % datetime.now())

def start_polling():
    """ Starts the bot """
    try:

        bot.skip_pending = True
        print(f'Bot {bot.get_me().username} started')
        bot.polling()
    except Exception as e:
        print(e)
        
# 1. Start polling
start_polling()

# 2. Start the scheduler ==> Prevent bot to fall asleep
scheduler = BlockingScheduler()
scheduler.add_job(cronjob, "interval", seconds=300)
scheduler.start()

Solution

  • A Web dyno will go to sleep after 30 min without incoming HTTP requests. You cannot prevent that in any way (i.e. running some background code).

    You have 2 options:

    • keep it alive by executing a request (every x min) from an external schedule, like Kaffeine
    • convert the Dyno to worker. If you don't need to receive incoming requests (for example you Bot is only polling) this is a good solution: the Dyno will not sleep and you won't need to use external tools.