Note
The django API is a slightly simplified version of the general python API. For details on using the django API, read here
Most end-users will interact with the API using the two decorators in huey.decorators:
Each decorator takes an Invoker instance – the Invoker is responsible for coordinating with the various backends (the message queue, the result store if you’re using one, scheduling commands, etc). The API documentation will follow the structure of the huey API, starting with the highest-level interfaces (the decorators) and eventually discussing the lowest-level interfaces, the BaseQueue and BaseDataStore objects.
Function decorator that marks the decorated function for processing by the consumer. Calls to the decorated function will do the following:
Note
The Invoker can be configured to execute the function immediately by instantiating it with always_eager = True – this is useful for running in debug mode or when you do not wish to run the consumer.
Here is how you might use the queue_command decorator:
# assume that we've created an invoker alongside the rest of the
# config
from config import invoker
from huey.decorators import queue_command
@queue_command(invoker)
def count_some_beans(num):
# do some counting!
return 'Counted %s beans' % num
Now, whenever you call this function in your application, the actual processing will occur when the consumer dequeues the message and your application will continue along on its way.
Without a result store:
>>> res = count_some_beans(1000000)
>>> res is None
True
With a result store:
>>> res = count_some_beans(1000000)
>>> res
<huey.queue.AsyncData object at 0xb7471a4c>
>>> res.get()
'Counted 1000000 beans'
Parameters: |
|
---|---|
Return type: | decorated function |
The return value of any calls to the decorated function depends on whether the invoker is configured with a result store. If a result store is configured, the decorated function will return an AsyncData object which can fetch the result of the call from the result store – otherwise it will simply return None.
The queue_command decorator also does one other important thing – it adds a special function onto the decorated function, which makes it possible to schedule the execution for a certain time in the future:
Use the special .schedule() function to schedule the execution of a queue command for a given time in the future:
import datetime
# get a datetime object representing one hour in the future
in_an_hour = datetime.datetime.now() + datetime.timedelta(seconds=3600)
# schedule "count_some_beans" to run in an hour
count_some_beans.schedule(args=(100000,), eta=in_an_hour)
Parameters: |
|
---|---|
Return type: | like calls to the decorated function, will return an AsyncData object if a result store is configured, otherwise returns None |
Store a reference to the command class for the decorated function.
>>> count_some_beans.command_class
commands.queuecmd_count_beans
Function decorator that marks the decorated function for processing by the consumer at a specific interval. Calls to functions decorated with periodic_command will execute normally, unlike queue_command(), which enqueues commands for execution by the consumer. Rather, the periodic_command decorator serves to mark a function as needing to be executed periodically by the consumer.
Note
By default, the consumer will not execute periodic_command functions. To enable this, simply add PERIODIC = True to your configuration.
The validate_datetime parameter is a function which accepts a datetime object and returns a boolean value whether or not the decorated function should execute at that time or not. The consumer will send a datetime to the function every minute, giving it the same granularity as the linux crontab, which it was designed to mimic.
For simplicity, there is a special function crontab(), which can be used to quickly specify intervals at which a function should execute. It is described below.
Here is an example of how you might use the periodic_command decorator and the crontab helper:
from config import invoker
from huey.decorators import periodic_command, crontab
@periodic_command(invoker, crontab(minute='*/5'))
def every_five_minutes():
# this function gets executed every 5 minutes by the consumer
print "It's been five minutes"
Note
Because functions decorated with periodic_command are meant to be executed at intervals in isolation, they should not take any required parameters nor should they be expected to return a meaningful value. This is the same regardless of whether or not you are using a result store.
Parameters: |
|
---|---|
Return type: | decorated function |
Like queue_command(), the periodic command decorator adds several helpers to the decorated function. These helpers allow you to “revoke” and “restore” the periodic command, effectively enabling you to pause it or prevent its execution.
Prevent the given periodic command from executing. When no parameters are provided the function will not execute again.
This function can be called multiple times, but each call will overwrite the limitations of the previous.
Parameters: |
|
---|
# skip the next execution
every_five_minutes.revoke(revoke_once=True)
# pause the command indefinitely
every_five_minutes.revoke()
# pause the command for 24 hours
every_five_minutes.revoke(datetime.datetime.now() + datetime.timedelta(days=1))
Check whether the given periodic command is revoked. If dt is specified, it will check if the command is revoked for the given datetime.
Parameters: | dt (datetime) – If provided, checks whether command is revoked at the given datetime |
---|
Clears any revoked status and run the command normally
If you want access to the underlying command class, it is stored as an attribute on the decorated function:
Store a reference to the command class for the decorated function.
Convert a “crontab”-style set of parameters into a test function that will return True when a given datetime matches the parameters set forth in the crontab.
Acceptable inputs:
Return type: | a test function that takes a datetime and returns a boolean |
---|
The Invoker ties together your application’s queue, result store, and supplies some options to configure how tasks are executed and how their results are stored.
Applications will have at least one Invoker instance, as it is required by the function decorators. Typically it should be instantiated along with the Queue, or wherever you create your configuration.
Example:
from huey.backends.redis_backend import RedisBlockingQueue, RedisDataStore
from huey.queue import Invoker
queue = RedisBlockingQueue('test-queue', host='localhost', port=6379)
result_store = RedisDataStore('results', host='localhost', port=6379)
# Create an invoker instance, which points at the queue and result store
# which are used by the application's Configuraiton object
invoker = Invoker(queue, result_store=result_store)
Although you will probably never instantiate an AsyncData object yourself, they are returned by any calls to queue_command() decorated functions (provided the invoker is configured with a result store). The AsyncData talks to the result store and is responsible for fetching results from tasks. Once the consumer finishes executing a task, the return value is placed in the result store, allowing the producer to retrieve it.
Working with the AsyncData class is very simple:
>>> from main import count_some_beans
>>> res = count_some_beans(100)
>>> res # <--- what is "res" ?
<huey.queue.AsyncData object at 0xb7471a4c>
>>> res.get() # <--- get the result of this task, assuming it executed
'Counted 100 beans'
What happens when data isn’t available yet? Let’s assume the next call takes about a minute to calculate:
>>> res = count_some_beans(10000000) # let's pretend this is slow
>>> res.get() # data is not ready, so returns None
>>> res.get() is None # data still not ready
True
>>> res.get(blocking=True, timeout=5) # block for 5 seconds
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/charles/tmp/huey/src/huey/huey/queue.py", line 46, in get
raise DataStoreTimeout
huey.exceptions.DataStoreTimeout
>>> res.get(blocking=True) # no timeout, will block until it gets data
'Counted 10000000 beans'
Attempt to retrieve the return value of a task. By default, it will simply ask for the value, returning None if it is not ready yet. If you want to wait for a value, you can specify blocking = True – this will loop, backing off up to the provided max_delay until the value is ready or until the timeout is reached. If the timeout is reached before the result is ready, a DataStoreTimeout exception will be raised.
Parameters: |
|
---|
Revoke the given command. Unless it is in the process of executing, it will be revoked and the command will not run.
in_an_hour = datetime.datetime.now() + datetime.timedelta(seconds=3600)
# run this command in an hour
res = count_some_beans.schedule(args=(100000,), eta=in_an_hour)
# oh shoot, I changed my mind, do not run it after all
res.revoke()
Applications using huey should subclass BaseConfiguration when specifying the configuration options to use. BaseConfiguration is where the queue, result store, and many other settings are configured. The configuration is then used by the consumer to access the queue. All configuration settings are class attributes.
An instance of a Queue class, which must be a subclass of BaseQueue. Tells consumer what queue to pull messages from.
An instance of a DataStore class, which must be a subclass of DataStore or None. Tells consumer where to store results of messages.
An instance of a DataStore class, which must be a subclass of DataStore or None. Tells consumer where to serialize the schedule of pending tasks in the event the consumer is shut down unexpectedly.
A boolean value indicating whether the consumer should enqueue periodic tasks
Number of worker threads to run
Whether to run using local now() or utcnow() when determining times to execute periodic commands and scheduled commands.
Huey communicates with two types of data stores – queues and datastores. Thinking of them as python datatypes, a queue is sort of like a list and a datastore is sort of like a dict. Queues are FIFOs that store tasks – producers put tasks in on one end and the consumer reads and executes tasks from the other. DataStores are key-based stores that can store arbitrary results of tasks keyed by task id. DataStores can also be used to serialize task schedules so in the event your consumer goes down you can bring it back up and not lose any tasks that had been scheduled.
Huey, like just about a zillion other projects, uses a “pluggable backend” approach, where the interface is defined on a couple classes BaseQueue and BaseDataStore, and you can write an implementation for any datastore you like. The project ships with backends that talk to redis, a fast key-based datastore, but the sky’s the limit when it comes to what you want to interface with. Below is an outline of the methods that must be implemented on each class.
Queue implementation – any connections that must be made should be created when instantiating this class.
Parameters: |
|
---|
Whether the backend blocks when waiting for new results. If set to False, the backend will be polled at intervals, if True it will read and wait.
Write data to the queue - has no return value.
Parameters: | data – a string |
---|
Read data from the queue, returning None if no data is available – an empty queue should not raise an Exception!
Return type: | a string message or None if no data is present |
---|
Optional: Delete everything in the queue – used by tests
Optional: Return the number of items in the queue – used by tests
Data store implementation – any connections that must be made should be created when instantiating this class.
Parameters: |
|
---|
Store the value using the key as the identifier
Retrieve the value stored at the given key, returns a special value EmptyData if no data exists at the given key. This is to differentiate between “no data” and a stored None value.
Warning
After a result is fetched it should be removed from the store!
Remove all keys
All the following use the python redis driver written by Andy McCurdy.
Does a simple RPOP to pull messages from the queue, meaning that it polls.
Parameters: |
|
---|
Does a BRPOP to pull messages from the queue, meaning that it blocks on reads.
Parameters: |
|
---|
Stores results in a redis hash using HSET, HGET and HDEL
Parameters: |
|
---|
Good news, the django api is considerably simpler! This is because django has very specific conventions for how things should be configured. If you’re using django you don’t have to worry about invokers or configuration objects – simply configure the queue and result store in the settings and use the decorators and management command to run the consumer.
Identical to the queue_command() described above, except that it takes no parameters.
from huey.djhuey.decorators import queue_command
@queue_command
def count_some_beans(how_many):
return 'Counted %s beans' % how_many
Identical to the periodic_command() described above, except that it does not take an invoker as its first argument.
from huey.djhuey.decorators import periodic_command, crontab
@periodic_command(crontab(minute='*/5'))
def every_five_minutes():
# this function gets executed every 5 minutes by the consumer
print "It's been five minutes"
All configuration occurs in the django settings module. Settings are configured using the same names as those in the python api with the exception that queues and data stores can be specified using a string module path, and connection keyword-arguments are specified using a dictionary.
Example configuration:
HUEY_CONFIG = {
'QUEUE': 'huey.backends.redis_backend.RedisQueue',
'QUEUE_CONNECTION': {
'host': 'localhost',
'port': 6379
},
'THREADS': 4,
}
Either a queue instance or a string pointing to the module path and class name of the queue. If a string is used, you may also need to specify a connection parameters.
Example: huey.backends.redis_backend.RedisQueue
QUEUE_NAME (string), default = database name
Either a DataStore instance or a string pointing to the module path and class name of the result store.
Example: huey.backends.redis_backend.RedisDataStore
RESULT_STORE_NAME (string), default = database name
LOGFILE (string), default = None
LOGLEVEL (int), default = logging.INFO