X Tutup
Skip to content

Commit 3aedd78

Browse files
committed
make job queue API similar to the dispatcher, add new functionality
1 parent d90b0f4 commit 3aedd78

File tree

6 files changed

+258
-86
lines changed

6 files changed

+258
-86
lines changed

README.rst

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -395,23 +395,53 @@ The ``JobQueue`` allows you to perform tasks with a delay or even periodically.
395395
>>> u = Updater('TOKEN')
396396
>>> j = u.job_queue
397397
398-
The job queue uses functions for tasks, so we define one and add it to the queue. Usually, when the first job is added to the queue, it wil start automatically. We can prevent this by setting ``prevent_autostart=True``:
398+
The job queue uses the ``Job`` class for tasks. We define a callback function, instantiate a ``Job`` and add it to the queue.
399+
400+
Usually, when the first job is added to the queue, it wil start automatically. We can prevent this by setting ``prevent_autostart=True``:
399401

400402
.. code:: python
401403
402-
>>> def job1(bot):
404+
>>> from telegram.ext import Job
405+
>>> def callback_minute(bot, job):
403406
... bot.sendMessage(chat_id='@examplechannel', text='One message every minute')
404-
>>> j.put(job1, 60, next_t=0, prevent_autostart=True)
407+
...
408+
>>> job_minute = Job(callback_minute, 60.0, next_t=0.0)
409+
>>> j.put(job_minute, prevent_autostart=True)
405410
406-
You can also have a job that will not be executed repeatedly:
411+
You can also have a job that will be executed only once:
407412

408413
.. code:: python
409414
410-
>>> def job2(bot):
415+
>>> def callback_30(bot, job):
411416
... bot.sendMessage(chat_id='@examplechannel', text='A single message with 30s delay')
412-
>>> j.put(job2, 30, repeat=False)
417+
...
418+
>>> j.put(Job(callback_30, 30.0, repeat=False))
419+
420+
Now, because we didn't prevent the auto start this time, the queue will start working. It runs in a seperate thread, so it is non-blocking.
421+
422+
Jobs can be temporarily disabled or completely removed from the ``JobQueue``:
423+
424+
.. code:: python
425+
426+
>>> job_minute.enabled = False
427+
>>> job_minute.schedule_removal()
428+
429+
Please note that ``schedule_removal`` does not immediately removes the job from the queue. Instead, it is marked for removal and will be removed as soon as its current interval is over (it will not run again after being marked for removal).
430+
431+
A job can also change its own behaviour, as it is passed to the callback function as the second argument:
432+
433+
.. code:: python
434+
435+
>>> def callback_increasing(bot, job):
436+
... bot.sendMessage(chat_id='@examplechannel',
437+
... text='Sending messages with increasing delay up to 10s, then stops.')
438+
... job.interval += 1.0
439+
... if job.interval > 10.0:
440+
... job.schedule_removal()
441+
...
442+
>>> j.put(Job(callback_increasing, 1.0))
413443
414-
Now, because we didn't prevent the auto start this time, the queue will start ticking. It runs in a seperate thread, so it is non-blocking. When we stop the Updater, the related queue will be stopped as well:
444+
When we stop the Updater, the related queue will be stopped as well:
415445

416446
.. code:: python
417447

examples/timerbot.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,16 @@
1717
bot.
1818
"""
1919

20-
from telegram.ext import Updater, CommandHandler
20+
from telegram.ext import Updater, CommandHandler, Job
2121
import logging
2222

2323
# Enable logging
2424
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25-
level=logging.INFO)
25+
level=logging.DEBUG)
2626

2727
logger = logging.getLogger(__name__)
2828
job_queue = None
29+
timers = dict()
2930

3031

3132
# Define a few command handlers. These usually take the two arguments bot and
@@ -35,36 +36,50 @@ def start(bot, update):
3536

3637

3738
def set(bot, update, args):
38-
""" Adds a job to the queue """
39+
"""Adds a job to the queue"""
3940
chat_id = update.message.chat_id
4041
try:
4142
# args[0] should contain the time for the timer in seconds
4243
due = int(args[0])
4344
if due < 0:
4445
bot.sendMessage(chat_id, text='Sorry we can not go back to future!')
4546

46-
def alarm(bot):
47-
""" Inner function to send the alarm message """
47+
def alarm(bot, job):
48+
"""Inner function to send the alarm message"""
4849
bot.sendMessage(chat_id, text='Beep!')
4950

5051
# Add job to queue
51-
job_queue.put(alarm, due, repeat=False)
52+
job = Job(alarm, due, repeat=False)
53+
timers[chat_id] = job
54+
job_queue.put(job)
55+
5256
bot.sendMessage(chat_id, text='Timer successfully set!')
5357

54-
except IndexError:
55-
bot.sendMessage(chat_id, text='Usage: /set <seconds>')
56-
except ValueError:
58+
except (IndexError, ValueError):
5759
bot.sendMessage(chat_id, text='Usage: /set <seconds>')
5860

5961

62+
def unset(bot, update):
63+
"""Removes the job if the user changed their mind"""
64+
chat_id = update.message.chat_id
65+
66+
if chat_id not in timers:
67+
bot.sendMessage(chat_id, text='You have no active timer')
68+
return
69+
70+
job = timers[chat_id]
71+
job.schedule_removal()
72+
bot.sendMessage(chat_id, text='Timer successfully unset!')
73+
74+
6075
def error(bot, update, error):
6176
logger.warn('Update "%s" caused error "%s"' % (update, error))
6277

6378

6479
def main():
6580
global job_queue
6681

67-
updater = Updater("TOKEN")
82+
updater = Updater("148447715:AAH4M0gzPG11_mdQS1Qeb0Ex30I5-rw9bMY")
6883
job_queue = updater.job_queue
6984

7085
# Get the dispatcher to register handlers
@@ -74,6 +89,7 @@ def main():
7489
dp.add_handler(CommandHandler("start", start))
7590
dp.add_handler(CommandHandler("help", start))
7691
dp.add_handler(CommandHandler("set", set, pass_args=True))
92+
dp.add_handler(CommandHandler("unset", unset))
7793

7894
# log all errors
7995
dp.add_error_handler(error)

telegram/ext/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"""Extensions over the Telegram Bot API to facilitate bot making"""
2020

2121
from .dispatcher import Dispatcher
22-
from .jobqueue import JobQueue
22+
from .jobqueue import JobQueue, Job
2323
from .updater import Updater
2424
from .callbackqueryhandler import CallbackQueryHandler
2525
from .choseninlineresulthandler import ChosenInlineResultHandler
@@ -32,7 +32,7 @@
3232
from .stringregexhandler import StringRegexHandler
3333
from .typehandler import TypeHandler
3434

35-
__all__ = ('Dispatcher', 'JobQueue', 'Updater', 'CallbackQueryHandler',
36-
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
37-
'MessageHandler', 'Filters', 'RegexHandler', 'StringCommandHandler',
38-
'StringRegexHandler', 'TypeHandler')
35+
__all__ = ('Dispatcher', 'JobQueue', 'Job', 'Updater', 'CallbackQueryHandler',
36+
'ChosenInlineResultHandler', 'CommandHandler', 'Handler',
37+
'InlineQueryHandler', 'MessageHandler', 'Filters', 'RegexHandler',
38+
'StringCommandHandler', 'StringRegexHandler', 'TypeHandler')

0 commit comments

Comments
 (0)
X Tutup