1

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()

1 Answers1

4

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.
Beppe C
  • 11,256
  • 2
  • 19
  • 41
  • The project is separated into two parts, the Django app and the bot itself. Django app uses `web` dyno and the bot uses `worker` dyno, So for the Django app yes, It goes to sleep but once someone sends a request to it, it'll wake up again after a short delay. but as for the second option, although my bot is running on a `worker` dyno, it still falls asleep... – Amir Rezazadeh May 11 '21 at 17:27
  • It is because you have both a `web` and a `worker` Dyno, they both go to sleep if the Web dyno is inactive. A solo `worker` Dyno does not sleep. – Beppe C May 11 '21 at 20:16
  • if a `web` dyno is inactive then a solo `worker` won't sleep, right? so if I ping my Django/web dyno then it'll be okay? – Amir Rezazadeh May 11 '21 at 20:28
  • In my answer option #1 suggests pinging the Web Dyno so it stays up (problem solved). Option #2 works if you have a Proc file with only one worker (this wont sleep) – Beppe C May 11 '21 at 20:31