'How to stop a job while running in telegram bot

I'm working on a Telegram bot using python-telegram-bot and I want to stop running a telegram.job object.
for example I want to stop running this hello function while it is in while loop.

def hello(context):
    while True:
        context.bot.send_message(chat_id=context.job.context, text="Hi!")

I'm using the start command to call hello function and run a job:

def start(update,context):
    context.job_queue.run_once(hello, 10, context=update.message.chat_id, name=update.effective_chat.id)

And using the end command, I remove the job from job queue:

def end(update,context):
    for job in context.job_queue._queue.queue:
        if job[1].name == update.effective_chat.id:
            context.job_queue._queue.queue.remove(job)

The problem is when I use end command before starting of the job(at first 10 seconds) it works correctly and stops the job but when I use end command while running the job it does nothing because the running job is not in the job queue.

Do you have any idea? How can I stop the running job?



Solution 1:[1]

I don't think that there's a straight way to do it via PTB itself, but it's quite easy to program yourself. You always have access to context.bot_data dictionary.

So store a variable there like run_job_a = True and check it on each iteration of your loop. Then you'll be able to stop the job by changing it's value to False.

Solution 2:[2]

If omitting the while loop in your job function is an option for you, you could also start a repeating job. This way the job would be still in your job queue and you can easily stop it.

# job
def hello(context):
  context.bot.send_message(chat_id=context.job.context, text="Hi!")

# executing the job every second
def start(update,context):
  context.job_queue.run_repeating(hello, 1, context=update.message.chat_id, name=str(update.effective_chat.id))

# end the job
def end(update,context):
  current_jobs = context.job_queue.get_jobs_by_name(name)

  for job in current_jobs:
      job.schedule_removal()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mikhail Beliansky
Solution 2 cyc8