### Install pystalkd Source: https://github.com/menezes-/pystalkd/blob/master/README.md Installation commands for the pystalkd library via pip or source. ```bash pip install pystalkd ``` ```bash python setup.py install ``` -------------------------------- ### Complete Worker Example Source: https://context7.com/menezes-/pystalkd/llms.txt A comprehensive example demonstrating a worker that watches a tube, reserves jobs, processes them (including JSON parsing and error handling), and then deletes or buries them. Includes reconnection logic for socket errors and graceful shutdown on keyboard interrupt. ```python from pystalkd.Beanstalkd import Connection, CommandFailed, SocketError import json import time def process_job(job_data): """Process the job data - implement your logic here.""" print(f"Processing: {job_data}") # Simulate work time.sleep(0.1) return True def worker(host="localhost", port=11300, tube="tasks"): conn = Connection(host, port) conn.watch(tube) conn.ignore("default") print(f"Worker started, watching tube: {tube}") while True: try: # Wait for a job with timeout job = conn.reserve(timeout=30) if job is None: print("No job available, waiting...") continue try: # Parse job data data = json.loads(job.body) # Process the job if process_job(data): job.delete() print(f"Job {job.job_id} completed successfully") else: # Failed, bury for inspection job.bury() print(f"Job {job.job_id} failed, buried") except json.JSONDecodeError: print(f"Invalid JSON in job {job.job_id}, deleting") job.delete() except Exception as e: print(f"Error processing job {job.job_id}: {e}") # Release job back with delay for retry job.release(delay=60) except SocketError: print("Connection lost, reconnecting...") conn.reconnect() except KeyboardInterrupt: print("Shutting down worker...") break conn.close() # Run the worker # worker(tube="email-notifications") ``` -------------------------------- ### GET /reserve Source: https://context7.com/menezes-/pystalkd/llms.txt Fetches and reserves a job from watched tubes. ```APIDOC ## GET /reserve ### Description Fetches and reserves a job from watched tubes. Returns a Job object or None on timeout. ### Parameters #### Query Parameters - **timeout** (int/timedelta) - Optional - Seconds to wait for a job ### Response #### Success Response (200) - **job** (Job object) - The reserved job object ``` -------------------------------- ### Get Server Statistics Source: https://context7.com/menezes-/pystalkd/llms.txt Retrieve server-wide statistics such as total jobs, current connections, and maximum job size. Requires an active connection. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Get server-wide statistics stats = conn.stats() print(f"Total jobs: {stats['total-jobs']}") print(f"Current connections: {stats['current-connections']}") print(f"Max job size: {stats['max-job-size']}") ``` -------------------------------- ### Job Object Methods for Management Source: https://context7.com/menezes-/pystalkd/llms.txt Provides methods to interact with a reserved job, including accessing properties, getting statistics, requesting more processing time (touch), releasing it, or deleting it. ```python from pystalkd.Beanstalkd import Connection import json conn = Connection("localhost", 11300) conn.use("my-tube") conn.watch("my-tube") # Create a test job conn.put(json.dumps({"task": "example"})) # Reserve the job job = conn.reserve(0) # Access job properties print(f"Job ID: {job.job_id}") print(f"Job body: {job.body}") print(f"Body size: {job.size}") print(f"Is reserved: {job.reserved}") # Get job statistics stats = job.stats() print(f"Job state: {stats['state']}") print(f"Job priority: {stats['pri']}") # Request more time to process (touch) job.touch() # Release job back to ready queue job.release() ``` -------------------------------- ### Get Job Statistics Source: https://context7.com/menezes-/pystalkd/llms.txt Retrieve statistics for an individual job using its ID. This includes its current state, priority, time-to-run, and reserve count. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Get statistics for a specific job job_stats = conn.stats_job(12345) print(f"State: {job_stats['state']}") print(f"Priority: {job_stats['pri']}") print(f"Time to run: {job_stats['ttr']}") print(f"Reserves: {job_stats['reserves']}") ``` -------------------------------- ### Get Tube Statistics Source: https://context7.com/menezes-/pystalkd/llms.txt Fetch statistics for a specific tube, including ready, delayed, buried, and total jobs. Ensure the tube name is correct. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Get statistics for a specific tube tube_stats = conn.stats_tube("email-queue") print(f"Ready jobs: {tube_stats['current-jobs-ready']}") print(f"Delayed jobs: {tube_stats['current-jobs-delayed']}") print(f"Buried jobs: {tube_stats['current-jobs-buried']}") print(f"Total jobs: {tube_stats['total-jobs']}") ``` -------------------------------- ### Handle Connection Errors Source: https://context7.com/menezes-/pystalkd/llms.txt Catch `SocketError` when establishing a connection to the Beanstalkd server fails, for example, due to an incorrect address or network issues. ```python from pystalkd.Beanstalkd import Connection, SocketError conn = Connection("localhost", 11300) try: # Connection errors bad_conn = Connection("255.255.255.255", timeout=2) except SocketError as e: print(f"Connection failed: {e}") ``` -------------------------------- ### POST /put Source: https://context7.com/menezes-/pystalkd/llms.txt Inserts a new job into the currently used tube. ```APIDOC ## POST /put ### Description Inserts a new job into the currently used tube. Returns the job ID on success. ### Parameters #### Request Body - **data** (string) - Required - The job body - **priority** (int) - Optional - Job priority (lower is higher priority) - **delay** (int/timedelta) - Optional - Seconds before job becomes ready - **ttr** (int/timedelta) - Optional - Time-to-run in seconds ### Response #### Success Response (200) - **job_id** (int) - The ID of the created job ``` -------------------------------- ### Basic Connection and Job Management Source: https://github.com/menezes-/pystalkd/blob/master/README.md Establish a connection to a Beanstalkd server and perform basic put and reserve operations. ```python from pystalkd.Beanstalkd import Connection c = Connection("localhost", 11300) #if no argument is given default configuration is used c.put("hey!") job = c.reserve(0) print(job.body) # "hey!" ``` -------------------------------- ### Connect with Raw YAML Output Source: https://context7.com/menezes-/pystalkd/llms.txt Instantiate a connection without YAML parsing to receive raw string output from the server. Useful for inspecting raw responses. ```python conn_raw = Connection("localhost", 11300, parse_yaml=False) tubes_yaml = conn_raw.tubes() print(tubes_yaml) # "---\n- default - email-queue " ``` -------------------------------- ### Retrieve Jobs as Binary Data with reserve_bytes Source: https://context7.com/menezes-/pystalkd/llms.txt Fetches jobs and returns the body as raw bytes. Useful for processing binary data or when the original encoding is unknown. Requires manual decoding or unpickling. ```python from pystalkd.Beanstalkd import Connection import pickle conn = Connection("localhost", 11300) # Reserve job as bytes job = conn.reserve_bytes(timeout=5) if job: print(f"Raw bytes: {job.body}") # b'...' # # Decode if it was originally a string text = job.body.decode('utf-8') # Or unpickle if it was pickled data # data = pickle.loads(job.body) job.delete() ``` -------------------------------- ### POST /put_bytes Source: https://context7.com/menezes-/pystalkd/llms.txt Inserts binary data as a job into the currently used tube. ```APIDOC ## POST /put_bytes ### Description Inserts binary data as a job, useful for serialized objects or raw bytes. ### Parameters #### Request Body - **data** (bytes) - Required - The binary job body ### Response #### Success Response (200) - **job_id** (int) - The ID of the created job ``` -------------------------------- ### use - Select Producer Tube Source: https://context7.com/menezes-/pystalkd/llms.txt The `use` method selects the tube where subsequent `put` commands will insert jobs. It allows you to route jobs to specific queues. ```APIDOC ## use - Select Producer Tube ### Description The `use` method selects the tube where subsequent `put` commands will insert jobs. ### Method `conn.use(tube_name: str)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Switch to a specific tube conn.use("email-queue") # Check current tube being used current = conn.using() print(f"Currently using: {current}") # Put job goes into the currently used tube conn.put("Send welcome email to user@example.com") ``` ### Response #### Success Response (200) Typically returns the name of the tube being used. #### Response Example ```json "email-queue" ``` ``` -------------------------------- ### Select Producer Tube Source: https://context7.com/menezes-/pystalkd/llms.txt Use the use method to define the target tube for subsequent put commands. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Switch to a specific tube conn.use("email-queue") # Check current tube being used current = conn.using() print(f"Currently using: {current}") # "email-queue" # Put job goes into the currently used tube conn.put("Send welcome email to user@example.com") # Switch to another tube conn.use("notification-queue") conn.put("Push notification data") ``` -------------------------------- ### temporary_use - Context Manager for Tube Usage Source: https://context7.com/menezes-/pystalkd/llms.txt The `temporary_use` context manager temporarily switches to a specified tube and automatically switches back to the original tube when the block is exited. ```APIDOC ## temporary_use - Context Manager for Tube Usage ### Description The `temporary_use` context manager temporarily switches to a tube and automatically switches back when done. ### Method `with conn.temporary_use(tube_name: str):` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) print(f"Default tube: {conn.using()}") with conn.temporary_use("processing-queue"): print(f"Inside context: {conn.using()}") conn.put("Job for processing queue") print(f"After context: {conn.using()}") def send_to_queue(conn, queue_name, message): with conn.temporary_use(queue_name): return conn.put(message) job_id = send_to_queue(conn, "high-priority", "Urgent task") ``` ### Response #### Success Response (200) No direct return value for the context manager itself, but operations within the `with` block succeed. #### Response Example None ``` -------------------------------- ### Run Tests Source: https://github.com/menezes-/pystalkd/blob/master/README.md Commands to execute the test suite against a local or remote Beanstalkd instance. ```bash python3 test.py ``` ```bash python3 test.py host [port] ``` -------------------------------- ### Temporary Tube Usage Source: https://github.com/menezes-/pystalkd/blob/master/README.md Use the 'with' keyword to temporarily switch the active tube or watch list. ```python from pystalkd.Beanstalkd import Connection c = Connection("localhost", 11300) print(c.using()) # "default" with c.temporary_use("test"): print(c.using()) # "test" print(c.using()) # "default" print(c.watching()) # ["default"] with c.temporary_use("test"): print(c.watching()) # ["default", "test"] print(c.watching()) # ["default"] ``` -------------------------------- ### List All Tubes Source: https://context7.com/menezes-/pystalkd/llms.txt Retrieve a list of all tubes currently existing on the server. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Get all tubes all_tubes = conn.tubes() print(f"Available tubes: {all_tubes}") # ['default', 'email-queue', 'notification-queue'] ``` -------------------------------- ### watch and ignore - Manage Consumer Tubes Source: https://context7.com/menezes-/pystalkd/llms.txt The `watch` and `ignore` methods control which tubes are monitored when reserving jobs. `watch` adds a tube to the list of monitored tubes, and `ignore` removes one. ```APIDOC ## watch and ignore - Manage Consumer Tubes ### Description The `watch` and `ignore` methods control which tubes are monitored when reserving jobs. ### Method `conn.watch(tube_name: str)` `conn.ignore(tube_name: str)` `conn.watching() -> list[str]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Watch a tube (start receiving jobs from it) count = conn.watch("email-queue") print(f"Now watching {count} tubes") # Watch multiple tubes conn.watch("notification-queue") conn.watch("sms-queue") # List all watched tubes watched = conn.watching() print(f"Watching: {watched}") # Stop watching a tube remaining = conn.ignore("default") print(f"Now watching {remaining} tubes") # Reserve will now get jobs from any watched tube job = conn.reserve(0) ``` ### Response #### Success Response (200) `watch` and `ignore` return the number of tubes currently being watched. `watching` returns a list of tube names. #### Response Example ```json // For watch/ignore: 3 // For watching: ["default", "email-queue", "notification-queue", "sms-queue"] ``` ``` -------------------------------- ### temporary_watch - Context Manager for Tube Watching Source: https://context7.com/menezes-/pystalkd/llms.txt The `temporary_watch` context manager temporarily watches a specified tube and automatically ignores it when the block is exited, reverting to the previous watching state. ```APIDOC ## temporary_watch - Context Manager for Tube Watching ### Description The `temporary_watch` context manager temporarily watches a tube and automatically ignores it when done. ### Method `with conn.temporary_watch(tube_name: str):` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) print(f"Initially watching: {conn.watching()}") with conn.temporary_watch("special-queue"): print(f"Inside context: {conn.watching()}") job = conn.reserve(0) # Can receive from both tubes print(f"After context: {conn.watching()}") ``` ### Response #### Success Response (200) No direct return value for the context manager itself, but operations within the `with` block succeed. #### Response Example None ``` -------------------------------- ### Manage Consumer Tubes Source: https://context7.com/menezes-/pystalkd/llms.txt Control which tubes are monitored for job reservation using watch and ignore. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Watch a tube (start receiving jobs from it) count = conn.watch("email-queue") print(f"Now watching {count} tubes") # Watch multiple tubes conn.watch("notification-queue") conn.watch("sms-queue") # List all watched tubes watched = conn.watching() print(f"Watching: {watched}") # ['default', 'email-queue', 'notification-queue', 'sms-queue'] # Stop watching a tube remaining = conn.ignore("default") print(f"Now watching {remaining} tubes") # Reserve will now get jobs from any watched tube job = conn.reserve(0) ``` -------------------------------- ### Use Temporary Tube Context Manager Source: https://context7.com/menezes-/pystalkd/llms.txt The temporary_use context manager automatically reverts the tube selection after the block completes. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) print(f"Default tube: {conn.using()}") # "default" with conn.temporary_use("processing-queue"): print(f"Inside context: {conn.using()}") # "processing-queue" conn.put("Job for processing queue") print(f"After context: {conn.using()}") # "default" # Useful for routing jobs to specific tubes def send_to_queue(conn, queue_name, message): with conn.temporary_use(queue_name): return conn.put(message) job_id = send_to_queue(conn, "high-priority", "Urgent task") ``` -------------------------------- ### tubes - List All Tubes Source: https://context7.com/menezes-/pystalkd/llms.txt The `tubes` method returns a list of all existing tubes on the Beanstalkd server, providing an overview of available queues. ```APIDOC ## tubes - List All Tubes ### Description The `tubes` method returns a list of all existing tubes on the server. ### Method `conn.tubes() -> list[str]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Get all tubes all_tubes = conn.tubes() print(f"Available tubes: {all_tubes}") ``` ### Response #### Success Response (200) A list of strings, where each string is the name of a tube. #### Response Example ```json ["default", "email-queue", "notification-queue"] ``` ``` -------------------------------- ### Connect to Beanstalkd Server Source: https://context7.com/menezes-/pystalkd/llms.txt Establishes a connection to the Beanstalkd server. Supports default, specific host/port, custom timeouts, and disabling YAML parsing for statistics. ```python from pystalkd.Beanstalkd import Connection # Connect with default settings (localhost:11300) conn = Connection() # Connect to a specific host and port conn = Connection("localhost", 11300) # Connect with custom timeout (in seconds) conn = Connection("localhost", 11300, connect_timeout=5) # Disable YAML parsing for stats (returns raw YAML strings) conn = Connection("localhost", 11300, parse_yaml=False) # Close connection when done conn.close() # Reconnect if connection was lost conn.reconnect() ``` -------------------------------- ### Manage Jobs via Connection Source: https://context7.com/menezes-/pystalkd/llms.txt Perform job management operations directly on the connection using job IDs. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Delete a job by ID conn.delete(12345) # Release a reserved job back to ready queue conn.release(job_id=12345, priority=1000, delay=30) # Bury a job conn.bury(job_id=12345, priority=1000) # Touch a job (extend TTR) conn.touch(job_id=12345) ``` -------------------------------- ### peek - Inspect Jobs Without Reserving Source: https://context7.com/menezes-/pystalkd/llms.txt The `peek` methods allow inspection of jobs in various states (specific ID, ready, delayed, buried) without affecting their status or reserving them. ```APIDOC ## peek - Inspect Jobs Without Reserving ### Description The `peek` methods allow inspection of jobs in various states without affecting their status. ### Method `conn.peek(job_id: int)` `conn.peek_ready()` `conn.peek_delayed()` `conn.peek_buried()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) conn.use("my-tube") conn.watch("my-tube") # Peek at a specific job by ID job = conn.peek(12345) if job: print(f"Job {job.job_id}: {job.body}") # Peek at next ready job job = conn.peek_ready() if job: print(f"Next ready job: {job.body}") else: print("No ready jobs") # Peek at next delayed job job = conn.peek_delayed() if job: print(f"Next delayed job: {job.body}") # Peek at next buried job job = conn.peek_buried() if job: print(f"Next buried job: {job.body}") ``` ### Response #### Success Response (200) Returns a `Job` object if a job is found, otherwise returns `None`. #### Response Example ```json // If job found: { "job_id": 12345, "body": "Job data", "tube": "my-tube", "state": "ready" } // If no job found: null ``` ``` -------------------------------- ### Inspect Jobs Without Reserving Source: https://context7.com/menezes-/pystalkd/llms.txt Use peek methods to view job details in specific states without changing their status. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) conn.use("my-tube") conn.watch("my-tube") # Peek at a specific job by ID job = conn.peek(12345) if job: print(f"Job {job.job_id}: {job.body}") # Peek at next ready job job = conn.peek_ready() if job: print(f"Next ready job: {job.body}") else: print("No ready jobs") # Peek at next delayed job job = conn.peek_delayed() if job: print(f"Next delayed job: {job.body}") # Peek at next buried job job = conn.peek_buried() if job: print(f"Next buried job: {job.body}") ``` -------------------------------- ### Retrieve Jobs from Queue with reserve Source: https://context7.com/menezes-/pystalkd/llms.txt Fetches and reserves a job from watched tubes. Can block indefinitely or with a specified timeout (integer or timedelta). Returns a Job object or None. ```python from pystalkd.Beanstalkd import Connection from datetime import timedelta conn = Connection("localhost", 11300) # Block indefinitely until a job is available job = conn.reserve() print(f"Job ID: {job.job_id}") print(f"Job body: {job.body}") # Reserve with timeout (seconds), returns None if no job available job = conn.reserve(timeout=5) if job: print(f"Got job: {job.body}") else: print("No job available within timeout") # Using timedelta for timeout job = conn.reserve(timeout=timedelta(seconds=30)) # Reserve with zero timeout (non-blocking) job = conn.reserve(0) ``` -------------------------------- ### Watch Temporary Tube Context Manager Source: https://context7.com/menezes-/pystalkd/llms.txt The temporary_watch context manager temporarily adds a tube to the watch list and removes it upon exit. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) print(f"Initially watching: {conn.watching()}") # ['default'] with conn.temporary_watch("special-queue"): print(f"Inside context: {conn.watching()}") # ['default', 'special-queue'] job = conn.reserve(0) # Can receive from both tubes print(f"After context: {conn.watching()}") # ['default'] ``` -------------------------------- ### Working with Bytes API Source: https://github.com/menezes-/pystalkd/blob/master/README.md Use methods ending in '_bytes' to interact with raw byte data instead of strings. ```python from pystalkd.Beanstalkd import Connection c = Connection("localhost", 11300) from os import urandom test_bytes = urandom(50) job_id = c.put_bytes(test_bytes) job = c.reserve_bytes(0) print(job.body) # b'i\x91\xdf\xf8\x1b?zj....' job_id2 = c.put("string") job2 = c.reserve_bytes(0) print(job2.body) # b'string' ``` -------------------------------- ### kick - Reactivate Buried or Delayed Jobs Source: https://context7.com/menezes-/pystalkd/llms.txt The `kick` methods move buried or delayed jobs back to the ready queue, making them available for reservation. `kick` affects multiple jobs, while `kick_job` targets a specific job. ```APIDOC ## kick - Reactivate Buried or Delayed Jobs ### Description The `kick` method moves buried or delayed jobs back to the ready queue. ### Method `conn.kick(bound: int)` `conn.kick_job(job_id: int)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) conn.use("my-tube") conn.watch("my-tube") # Kick up to N jobs back to ready queue kicked_count = conn.kick(10) print(f"Kicked {kicked_count} jobs") # Kick a specific job by ID conn.kick_job(12345) ``` ### Response #### Success Response (200) `kick` returns the number of jobs kicked. `kick_job` typically returns nothing on success. #### Response Example ```json // For kick: 5 // For kick_job: (No explicit return value on success) ``` ``` -------------------------------- ### Connection Management Source: https://context7.com/menezes-/pystalkd/llms.txt Methods for establishing and managing connections to the Beanstalkd server. ```APIDOC ## Connection ### Description Establishes a connection to a Beanstalkd server and provides methods for interacting with the queue system. ### Method Constructor ### Parameters #### Request Body - **host** (string) - Optional - Server hostname (default: localhost) - **port** (int) - Optional - Server port (default: 11300) - **connect_timeout** (int) - Optional - Connection timeout in seconds - **parse_yaml** (bool) - Optional - Whether to parse statistics as YAML (default: True) ``` -------------------------------- ### delete, release, bury, touch - Job Management via Connection Source: https://context7.com/menezes-/pystalkd/llms.txt These methods allow direct management of jobs by their ID using the `Connection` object, enabling deletion, release, burying, or touching (extending TTR) of jobs. ```APIDOC ## delete, release, bury, touch - Job Management via Connection ### Description These Connection methods manage jobs directly by job ID without needing a Job object. ### Method `conn.delete(job_id: int)` `conn.release(job_id: int, priority: int = 0, delay: int = 0)` `conn.bury(job_id: int, priority: int = 0)` `conn.touch(job_id: int)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Delete a job by ID conn.delete(12345) # Release a reserved job back to ready queue conn.release(job_id=12345, priority=1000, delay=30) # Bury a job conn.bury(job_id=12345, priority=1000) # Touch a job (extend TTR) conn.touch(job_id=12345) ``` ### Response #### Success Response (200) These operations typically return nothing on success or a simple success indicator. #### Response Example None ``` -------------------------------- ### Add Binary Jobs to Queue with put_bytes Source: https://context7.com/menezes-/pystalkd/llms.txt Inserts binary data as a job into the queue. Useful for serialized objects (like pickle) or raw bytes. ```python from pystalkd.Beanstalkd import Connection from os import urandom import json import pickle conn = Connection("localhost", 11300) # Put raw bytes binary_data = urandom(50) job_id = conn.put_bytes(binary_data) # Put pickled Python object data = {"user_id": 123, "action": "process"} pickled = pickle.dumps(data) job_id = conn.put_bytes(pickled) # Put JSON as bytes json_bytes = json.dumps({"key": "value"}).encode('utf-8') job_id = conn.put_bytes(json_bytes) ``` -------------------------------- ### Add Jobs to Queue with put Source: https://context7.com/menezes-/pystalkd/llms.txt Inserts a new job into the currently used tube. Supports custom priority, delay, and time-to-run (TTR) using integers or timedelta objects. ```python from pystalkd.Beanstalkd import Connection from datetime import timedelta conn = Connection("localhost", 11300) # Simple job with default settings job_id = conn.put("Hello, World!") print(f"Created job with ID: {job_id}") # Job with custom priority (lower = higher priority, default is 2^31) job_id = conn.put("High priority task", priority=100) # Job with delay (seconds before becoming ready) job_id = conn.put("Delayed task", delay=60) # Job with custom time-to-run (TTR) in seconds job_id = conn.put("Long running task", ttr=300) # Using timedelta for delay and TTR job_id = conn.put("Scheduled task", delay=timedelta(hours=1), ttr=timedelta(minutes=10)) # Full options example job_id = conn.put( "Complete job configuration", priority=1000, delay=30, ttr=120 ) ``` -------------------------------- ### Pause Tube Delivery (Timedelta) Source: https://context7.com/menezes-/pystalkd/llms.txt Pause job reservations from a tube using a `timedelta` object for precise duration control. Useful for scheduling pauses. ```python from pystalkd.Beanstalkd import Connection from datetime import timedelta conn = Connection("localhost", 11300) # Using timedelta conn.pause_tube("email-queue", delay=timedelta(minutes=5)) ``` -------------------------------- ### Handle Server Errors (Job Too Big) Source: https://context7.com/menezes-/pystalkd/llms.txt Catch `CommandFailed` for server-side errors like attempting to put a job that exceeds the maximum allowed size. The exception message will indicate the specific error. ```python from pystalkd.Beanstalkd import Connection, CommandFailed conn = Connection("localhost", 11300) try: # Server errors conn.put("x" * 100000000) # Job too big except CommandFailed as e: print(f"Job rejected: {e}") # "JOB_TOO_BIG" ``` -------------------------------- ### Handle Deadline Soon Exception Source: https://context7.com/menezes-/pystalkd/llms.txt Catch `DeadlineSoon` when reserving a job whose time-to-run is about to expire. This indicates a potential issue with job processing time. ```python from pystalkd.Beanstalkd import Connection, DeadlineSoon conn = Connection("localhost", 11300) try: # Deadline approaching on reserved job job = conn.reserve() except DeadlineSoon as e: print(f"Job deadline approaching: {e}") ``` -------------------------------- ### Reactivate Buried or Delayed Jobs Source: https://context7.com/menezes-/pystalkd/llms.txt Move jobs back to the ready queue using kick or kick_job. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) conn.use("my-tube") conn.watch("my-tube") # Kick up to N jobs back to ready queue # First kicks buried jobs, then delayed jobs if no buried jobs exist kicked_count = conn.kick(10) print(f"Kicked {kicked_count} jobs") # Kick a specific job by ID conn.kick_job(12345) ``` -------------------------------- ### Handle Command Failures Source: https://context7.com/menezes-/pystalkd/llms.txt Catch `CommandFailed` exceptions for operations that do not succeed on the server, such as attempting to delete a non-existent job. ```python from pystalkd.Beanstalkd import Connection, CommandFailed conn = Connection("localhost", 11300) try: # Command failures (e.g., job not found) conn.delete(999999999) except CommandFailed as e: print(f"Command failed: {e}") # "NOT_FOUND" ``` -------------------------------- ### Manage Job Lifecycle Source: https://context7.com/menezes-/pystalkd/llms.txt Methods for modifying the state of a reserved job, such as releasing, burying, kicking, or deleting it. ```python # Or release with new priority and delay job = conn.reserve(0) job.release(priority=500, delay=10) # Bury job (move to buried state for later inspection) job = conn.reserve(0) job.bury() # Kick a buried/delayed job back to ready queue job.kick() # Delete job when processing is complete job = conn.reserve(0) job.delete() ``` -------------------------------- ### Pause Tube Delivery (Seconds) Source: https://context7.com/menezes-/pystalkd/llms.txt Temporarily pause job reservations from a specific tube for a given number of seconds. Jobs will not be reserved until the delay expires. ```python from pystalkd.Beanstalkd import Connection conn = Connection("localhost", 11300) # Pause tube for 60 seconds conn.pause_tube("email-queue", delay=60) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.