read_messages: list[Message] = queue.read_batch("my_queue", vt=30, batch_size=5)
for message in read_messages:
print(message)
Read messages with polling
The read_with_poll method allows you to repeatedly check for messages in the queue until either a message is found or the specified polling duration is exceeded. This can be useful in scenarios where you want to wait for new messages to arrive without continuously querying the queue in a tight loop.
In the following example, the method will check for up to 5 messages in the queue my_queue, making the messages invisible for 30 seconds (vt), and will poll for a maximum of 5 seconds (max_poll_seconds) with intervals of 100 milliseconds (poll_interval_ms) between checks.
read_messages: list[Message] = queue.read_with_poll(
"my_queue", vt=30, qty=5, max_poll_seconds=5, poll_interval_ms=100
)
for message in read_messages:
print(message)
This method will continue polling until it retrieves any messages, with a maximum of (qty) messages in a single poll, or until the max_poll_seconds duration is reached. The poll_interval_ms parameter controls the interval between successive polls, allowing you to avoid hammering the database with continuous queries.
The metrics method retrieves various statistics for a specific queue, such as the queue length, the age of the newest and oldest messages, the total number of messages, and the time of the metrics scrape.
To perform multiple operations within a single transaction, use the @transaction decorator from the tembo_pgmq_python.decorators module.
This ensures that all operations within the function are executed within the same transaction and are either committed together or rolled back if an error occurs.
First, import the transaction decorator:
from tembo_pgmq_python.decorators import transaction
Example: Transactional Operation
@transaction
def transactional_operation(queue: PGMQueue, conn=None):
# Perform multiple queue operations within a transaction
queue.create_queue("transactional_queue", conn=conn)
queue.send("transactional_queue", {"message": "Hello, World!"}, conn=conn)
To execute the transaction:
try:
transactional_operation(queue)
except Exception as e:
print(f"Transaction failed: {e}")
In this example, the transactional_operation function is decorated with @transaction, ensuring all operations inside it are part of a single transaction. If an error occurs, the entire transaction is rolled back automatically.
Alternatives
Use instead of tembo-pgmq-python: tools that do the same job, closest first.