### Install aioschedule using pip Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/README.rst This command installs the aioschedule library using pip, the Python package installer. Ensure you have pip installed and configured correctly. ```bash pip install aioschedule ``` -------------------------------- ### Complete Asynchronous Application Lifecycle Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt A comprehensive example demonstrating job tagging, lifecycle management, and dynamic scheduling with time limits. It shows how to manage a collection of jobs and handle graceful shutdown. ```python import asyncio import aioschedule as schedule from datetime import timedelta # Job functions async def fetch_data(): print("Fetching data from API...") await asyncio.sleep(0.5) # Simulate API call print("Data fetched successfully") async def process_queue(): print("Processing message queue...") await asyncio.sleep(0.2) print("Queue processed") async def cleanup(): print("Running cleanup...") return schedule.CancelJob # Run once then cancel async def health_check(): print("Health check: OK") # Configure jobs with tags schedule.every(30).seconds.do(fetch_data).tag("api", "data") schedule.every(10).seconds.do(process_queue).tag("queue") schedule.every(5).seconds.do(health_check).tag("monitoring") schedule.every().minute.do(cleanup).tag("maintenance") # Set deadline for queue processing (run for 1 hour) schedule.every(10).seconds.until(timedelta(hours=1)).do(process_queue).tag("queue", "limited") async def main(): print("Scheduler started") print(f"Total jobs: {len(schedule.get_jobs())}") print(f"API jobs: {len(schedule.get_jobs('api'))}") try: while schedule.get_jobs(): await schedule.run_pending() idle = schedule.idle_seconds() if idle and idle > 0: await asyncio.sleep(min(idle, 1)) else: await asyncio.sleep(0.1) except KeyboardInterrupt: print("Shutting down...") schedule.clear() asyncio.run(main()) ``` -------------------------------- ### Initialize and Run Multiple Schedulers Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/multiple-schedulers.md This example shows how to create multiple instances of the schedule.Scheduler class. It demonstrates registering distinct jobs to each scheduler and executing them within a single main loop. ```python import time import schedule def fooJob(): print("Foo") def barJob(): print("Bar") # Create a new scheduler scheduler1 = schedule.Scheduler() # Add jobs to the created scheduler scheduler1.every().hour.do(fooJob) scheduler1.every().hour.do(barJob) # Create as many schedulers as you need scheduler2 = schedule.Scheduler() scheduler2.every().second.do(fooJob) scheduler2.every().second.do(barJob) while True: # run_pending needs to be called on every scheduler scheduler1.run_pending() scheduler2.run_pending() time.sleep(1) ``` -------------------------------- ### Install pytz dependency Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/timezones.md Command to install the pytz library, which is required for timezone support in aioschedule. ```bash pip install pytz ``` -------------------------------- ### Timezone Support for Scheduling with at(tz) in Python Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Illustrates how to use the `at()` method with a timezone parameter to schedule jobs in specific timezones. This requires the `pytz` library to be installed. ```python import asyncio import aioschedule as schedule from pytz import timezone async def job(): print("Timezone-aware job running") # Using timezone string schedule.every().day.at("12:42", "Europe/Amsterdam").do(job) # Using pytz timezone object schedule.every().friday.at("12:42", timezone("Africa/Lagos")).do(job) # Job scheduled for 10:30 AM New York time # Will run at the correct local time regardless of server timezone schedule.every().day.at("10:30", "America/New_York").do(job) async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Python: Schedule Job at Random Intervals Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/FAQ.rst This example shows how to schedule a job to run at random intervals within a specified range. The `to()` method allows defining a minimum and maximum time between job executions. ```python import schedule def my_job(): # This job will execute every 5 to 10 seconds. print('Foo') schedule.every(5).to(10).seconds.do(my_job) ``` -------------------------------- ### Basic Job Scheduling Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/index.md This snippet demonstrates how to install and use aioschedule to schedule various types of jobs, including periodic, time-based, and day-specific tasks. ```APIDOC ## Installation ### Description Install the aioschedule library using pip. ### Method `pip install` ### Endpoint N/A ### Parameters None ### Request Example ```bash $ pip install aioschedule ``` ### Response N/A --- ## Basic Job Scheduling Example ### Description This example shows how to schedule different types of jobs using the aioschedule library and run them. ### Method `asyncio` and `aioschedule` ### Endpoint N/A ### Parameters None ### Request Example ```python import asyncio import aioschedule as schedule import time async def job(message='stuff', n=1): print("Asynchronous invocation (%s) of I'm working on:" % n, message) asyncio.sleep(1) for i in range(1,3): schedule.every(1).seconds.do(job, n=i) schedule.every(5).to(10).days.do(job) schedule.every().hour.do(job, message='things') schedule.every().day.at("10:30").do(job) schedule.every().monday.do(job) schedule.every().wednesday.at("13:15").do(job) schedule.every().day.at("12:42", "Europe/Amsterdam").do(job) schedule.every().minute.at(":17").do(job) loop = asyncio.get_event_loop() while True: loop.run_until_complete(schedule.run_pending()) time.sleep(0.1) ``` ### Response #### Success Response (200) N/A (This is a script execution, not an API response) #### Response Example Output will vary based on job execution timing. Example: ``` Asynchronous invocation (1) of I'm working on: stuff Asynchronous invocation (2) of I'm working on: stuff ``` ``` -------------------------------- ### Filter and Get Jobs by Tags (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Illustrates how to tag jobs with unique identifiers and then retrieve specific groups of jobs using `schedule.get_jobs(tag)`. This allows for managing and accessing related tasks efficiently. ```python import schedule def greet(name): print('Hello {}'.format(name)) schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend') schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend') schedule.every().hour.do(greet, 'Monica').tag('hourly-tasks', 'customer') schedule.every().day.do(greet, 'Derek').tag('daily-tasks', 'guest') friends = schedule.get_jobs('friend') # Will return a list of every job tagged as `friend`. ``` -------------------------------- ### Retrieve All Scheduled Jobs (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Shows how to get a list of all currently scheduled jobs using the `schedule.get_jobs()` method. This can be useful for inspecting the scheduler's current state or for debugging. ```python import schedule def hello(): print('Hello world') schedule.every().second.do(hello) all_jobs = schedule.get_jobs() ``` -------------------------------- ### Pass Arguments to Scheduled Jobs (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Shows how to pass arguments to scheduled job functions using the `do()` method. Extra arguments provided to `do()` are passed directly to the job function. The example also demonstrates using multiple `@repeat` decorators on a function, each with different scheduling parameters and arguments. ```python import schedule def greet(name): print('Hello', name) schedule.every(2).seconds.do(greet, name='Alice') schedule.every(4).seconds.do(greet, name='Bob') from schedule import every, repeat @repeat(every().second, "World") @repeat(every().day, "Mars") def hello(planet): print("Hello", planet) ``` -------------------------------- ### Python: Tag and Cancel Multiple Scheduled Jobs Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/FAQ.rst This example demonstrates how to tag scheduled jobs with custom identifiers and then cancel all jobs belonging to a specific tag. This is useful for managing groups of related tasks. ```python import schedule def greet(name): print('Hello {}'.format(name)) schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend') schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend') schedule.every().hour.do(greet, 'Monica').tag('hourly-tasks', 'customer') schedule.every().day.do(greet, 'Derek').tag('daily-tasks', 'guest') schedule.clear('daily-tasks') ``` -------------------------------- ### Schedule Jobs with aioschedule in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/README.rst This Python code demonstrates how to use the aioschedule library to schedule various types of jobs. It includes scheduling jobs at fixed intervals, within a time range, hourly, and daily at a specific time. The example utilizes asyncio for asynchronous job execution. ```python import asyncio import aioschedule as schedule import time async def job(message='stuff', n=1): print("Asynchronous invocation (%s) of I'm working on:" % n, message) asyncio.sleep(1) for i in range(1,3): schedule.every(1).seconds.do(job, n=i) schedule.every(5).to(10).days.do(job) schedule.every().hour.do(job, message='things') schedule.every().day.at("10:30").do(job) loop = asyncio.get_event_loop() while True: loop.run_until_complete(schedule.run_pending()) time.sleep(0.1) ``` -------------------------------- ### Schedule Periodic Jobs with aioschedule Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/index.md Example demonstrating how to schedule various types of periodic jobs using the aioschedule library in Python. It includes scheduling jobs at fixed intervals, within a range, at specific times, and on specific days. The scheduler runs in an infinite loop, checking for pending jobs. ```python import asyncio import aioschedule as schedule import time async def job(message='stuff', n=1): print("Asynchronous invocation (%s) of I'm working on:" % n, message) asyncio.sleep(1) for i in range(1,3): schedule.every(1).seconds.do(job, n=i) schedule.every(5).to(10).days.do(job) schedule.every().hour.do(job, message='things') schedule.every().day.at("10:30").do(job) schedule.every().monday.do(job) schedule.every().wednesday.at("13:15").do(job) schedule.every().day.at("12:42", "Europe/Amsterdam").do(job) schedule.every().minute.at(":17").do(job) loop = asyncio.get_event_loop() while True: loop.run_until_complete(schedule.run_pending()) time.sleep(0.1) ``` -------------------------------- ### Get next run time and idle seconds in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Introduces schedule.next_run() to get the next scheduled execution time and schedule.idle_seconds() to calculate the time until the next job. These functions are useful for monitoring and managing the scheduler's state. ```python import schedule import time def my_job(): pass schedule.every(10).seconds.do(my_job) while True: print(f"Next run at: {schedule.next_run()}") print(f"Idle seconds: {schedule.idle_seconds()}") schedule.run_pending() time.sleep(1) ``` -------------------------------- ### Python: Add Logging to Scheduled Jobs with a Decorator Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/FAQ.rst This Python decorator, `with_logging`, provides a simple way to add generic logging to scheduled job functions. It logs the start and completion of each job execution, helping to monitor job activity. ```python import functools import time import schedule def with_logging(func): @functools.wraps(func) def wrapper(*args, **kwargs): print('LOG: Running job "%s"' % func.__name__) result = func(*args, **kwargs) print('LOG: Job "%s" completed' % func.__name__) return result return wrapper @with_logging def job(): print('Hello, World.') schedule.every(3).seconds.do(job) while 1: schedule.run_pending() time.sleep(1) ``` -------------------------------- ### Get next run time and idle seconds Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Introduces `schedule.next_run()` to retrieve the next scheduled execution time and `schedule.idle_seconds()` to determine the time until the next job is due. These functions aid in monitoring and managing the scheduler's state. ```python next_run = schedule.next_run() idle = schedule.idle_seconds() ``` -------------------------------- ### Python aioschedule with Job Queue and Worker Threads Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/parallel-execution.md This example shows how to manage parallel execution using a shared job queue and multiple worker threads. It utilizes Python's `queue` module for thread-safe job distribution. The `worker_main` function continuously fetches jobs from the queue and executes them. Scheduled tasks are added to the queue using `jobqueue.put`. This method provides more control over the number of concurrent workers and is suitable for managing a large number of tasks. ```python import time import threading import schedule import queue def job(): print("I'm working") def worker_main(): while 1: job_func = jobqueue.get() job_func() jobqueue.task_done() jobqueue = queue.Queue() schedule.every(10).seconds.do(jobqueue.put, job) schedule.every(10).seconds.do(jobqueue.put, job) schedule.every(10).seconds.do(jobqueue.put, job) schedule.every(10).seconds.do(jobqueue.put, job) schedule.every(10).seconds.do(jobqueue.put, job) worker_thread = threading.Thread(target=worker_main) worker_thread.start() while 1: schedule.run_pending() time.sleep(1) ``` -------------------------------- ### Schedule Jobs Using Decorators (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Utilizes the `@repeat` decorator to schedule a function. The decorator accepts the same interval syntax as the `every()` method but omits the `.do()` call. This provides a more declarative way to schedule jobs. The example also notes that `@repeat` does not work on non-static class methods. ```python from schedule import every, repeat import time @repeat(every(10).minutes) def job(): print("I am a scheduled job") while True: run_pending() time.sleep(1) ``` -------------------------------- ### Run Python aioschedule Jobs in Separate Threads Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/parallel-execution.md This snippet demonstrates how to execute each scheduled job in its own thread to achieve parallel execution. It imports necessary libraries like threading, time, and schedule. The `run_threaded` function starts a new thread for the provided job function. This is useful for scenarios where independent tasks need to run concurrently without blocking the main scheduler. ```python import threading import time import schedule def job(): print("I'm running on thread %s" % threading.current_thread()) def run_threaded(job_func): job_thread = threading.Thread(target=job_func) job_thread.start() schedule.every(10).seconds.do(run_threaded, job) schedule.every(10).seconds.do(run_threaded, job) schedule.every(10).seconds.do(run_threaded, job) schedule.every(10).seconds.do(run_threaded, job) schedule.every(10).seconds.do(run_threaded, job) while 1: schedule.run_pending() time.sleep(1) ``` -------------------------------- ### Run aioschedule Jobs in Background Thread (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/background-execution.md This Python code snippet demonstrates how to run aioschedule jobs in a background thread. It defines a `run_continuously` function that starts a `ScheduleThread` to execute pending jobs at specified intervals without blocking the main thread. The `stop_run_continuously` event allows for graceful termination of the background thread. This approach is useful for applications where the main thread needs to remain responsive. ```python import threading import time import schedule def run_continuously(interval=1): """Continuously run, while executing pending jobs at each elapsed time interval. @return cease_continuous_run: threading. Event which can be set to cease continuous run. Please note that it is *intended behavior that run_continuously() does not run missed jobs*. For example, if you've registered a job that should run every minute and you set a continuous run interval of one hour then your job won't be run 60 times at each interval but only once. """ cease_continuous_run = threading.Event() class ScheduleThread(threading.Thread): @classmethod def run(cls): while not cease_continuous_run.is_set(): schedule.run_pending() time.sleep(interval) continuous_thread = ScheduleThread() continuous_thread.start() return cease_continuous_run def background_job(): print('Hello from the background thread') schedule.every().second.do(background_job) # Start the background thread stop_run_continuously = run_continuously() # Do some other things... time.sleep(10) # Stop the background thread stop_run_continuously.set() ``` -------------------------------- ### Configure Job Timing and Execution Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/reference.md Demonstrates how to schedule a job at a specific time, define a randomized interval, set an expiration deadline, and assign the task function. ```python import aioschedule as schedule import datetime def job(): print("Task running") # Schedule at specific time schedule.every().day.at("10:30").do(job) # Schedule with randomized interval schedule.every(5).to(10).seconds.do(job) # Schedule with expiration schedule.every().minute.until("2023-12-31 23:59:59").do(job) ``` -------------------------------- ### Schedule jobs with timezones Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/timezones.md Demonstrates how to schedule jobs using the .at() method by passing either a timezone string or a pytz timezone object. ```python import schedule from pytz import timezone # Pass a timezone as a string schedule.every().day.at("12:42", "Europe/Amsterdam").do(job) # Pass an pytz timezone object schedule.every().friday.at("12:42", timezone("Africa/Lagos")).do(job) ``` -------------------------------- ### Initialize and Run aioschedule Tasks Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/reference.md Demonstrates how to use the default scheduler to define a job and execute pending tasks asynchronously. This pattern is typical for event-loop driven applications. ```python import aioschedule import asyncio async def job(): print("Running task...") aioschedule.every(10).seconds.do(job) async def main(): while True: await aioschedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Basic Job Scheduling with every() in Python Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Demonstrates how to schedule asynchronous jobs at various fixed intervals using the `every()` function. Jobs are defined as async functions and executed periodically by the scheduler. ```python import asyncio import aioschedule as schedule async def job(): print("I'm working...") # Schedule jobs at various intervals schedule.every(3).seconds.do(job) # Every 3 seconds schedule.every(3).minutes.do(job) # Every 3 minutes schedule.every(3).hours.do(job) # Every 3 hours schedule.every(3).days.do(job) # Every 3 days schedule.every(3).weeks.do(job) # Every 3 weeks # Run the scheduler async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Custom Scheduler Instance Usage Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/reference.md Shows how to instantiate a custom Scheduler object instead of relying on the global default scheduler. This is useful for isolating task execution contexts. ```python from aioschedule import Scheduler scheduler = Scheduler() scheduler.every(5).minutes.do(my_async_func) # Run pending tasks on the specific scheduler instance await scheduler.run_pending() ``` -------------------------------- ### Schedule Jobs at Fixed Intervals and Times (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Demonstrates scheduling jobs at fixed intervals (seconds, minutes, hours, days, weeks) and at specific times of day or day of week. It also shows how to run jobs at specific seconds within a minute or minutes within an hour. The `run_pending()` function combined with `time.sleep(1)` is used to continuously check and run scheduled jobs. ```python import schedule import time def job(): print("I'm working...") # Run job every 3 second/minute/hour/day/week, # Starting 3 second/minute/hour/day/week from now schedule.every(3).seconds.do(job) schedule.every(3).minutes.do(job) schedule.every(3).hours.do(job) schedule.every(3).days.do(job) schedule.every(3).weeks.do(job) # Run job every minute at the 23rd second schedule.every().minute.at(":23").do(job) # Run job every hour at the 42rd minute schedule.every().hour.at(":42").do(job) # Run jobs every 5th hour, 20 minutes and 30 seconds in. # If current time is 02:00, first execution is at 06:20:30 schedule.every(5).hours.at("20:30").do(job) # Run job every day at specific HH:MM and next HH:MM:SS schedule.every().day.at("10:30").do(job) schedule.every().day.at("10:30:42").do(job) schedule.every().day.at("12:42", "Europe/Amsterdam").do(job) # Run job on a specific day of the week schedule.every().monday.do(job) schedule.every().wednesday.at("13:15").do(job) schedule.every().minute.at(":17").do(job) while True: schedule.run_pending() time.sleep(1) ``` -------------------------------- ### Scheduling Jobs at Specific Times with at() in Python Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Shows how to schedule jobs to run at precise times of the day or specific minutes/seconds using the `at()` method. This allows for more granular control over job execution timing. ```python import asyncio import aioschedule as schedule async def job(): print("Running scheduled task") # Daily jobs at specific times schedule.every().day.at("10:30").do(job) # Run at 10:30 AM schedule.every().day.at("10:30:42").do(job) # Run at 10:30:42 AM # Hourly jobs at specific minute schedule.every().hour.at(":42").do(job) # Run at 42 minutes past every hour schedule.every(5).hours.at("20:30").do(job) # Every 5 hours at 20:30 into the interval # Minute jobs at specific second schedule.every().minute.at(":23").do(job) # Run at 23 seconds past every minute # Weekly jobs on specific days schedule.every().monday.do(job) # Every Monday schedule.every().wednesday.at("13:15").do(job) # Every Wednesday at 1:15 PM async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Execute All Scheduled Jobs Immediately Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Demonstrates how to use the run_all() method to trigger all scheduled tasks immediately, regardless of their defined schedule. Jobs are automatically rescheduled after execution. ```python import asyncio import aioschedule as schedule async def job_1(): print("Foo") async def job_2(): print("Bar") schedule.every().monday.at("12:40").do(job_1) schedule.every().tuesday.at("16:40").do(job_2) async def main(): # Run all jobs immediately await schedule.run_all() print("All jobs executed") asyncio.run(main()) ``` -------------------------------- ### Passing Arguments to Scheduled Jobs with do() in Python Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Explains how to pass positional and keyword arguments to asynchronous job functions when scheduling them with the `do()` method. This enables dynamic data or configuration to be passed to scheduled tasks. ```python import asyncio import aioschedule as schedule async def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") async def process_data(data, verbose=False): if verbose: print(f"Processing: {data}") # Process data here # Pass positional and keyword arguments schedule.every(2).seconds.do(greet, "Alice") schedule.every(4).seconds.do(greet, "Bob", greeting="Hi") schedule.every().minute.do(process_data, {"key": "value"}, verbose=True) async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Implement Custom Job Logging Decorator Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/logging.md Demonstrates how to create a reusable decorator to log the execution time of scheduled jobs. This approach wraps existing job functions to provide custom logging output without modifying the job logic directly. ```python import functools import time import schedule def print_elapsed_time(func): @functools.wraps(func) def wrapper(*args, **kwargs): start_timestamp = time.time() print('LOG: Running job "%s"' % func.__name__) result = func(*args, **kwargs) print('LOG: Job "%s" completed in %d seconds' % (func.__name__, time.time() - start_timestamp)) return result return wrapper @print_elapsed_time def job(): print('Hello, Logs') time.sleep(5) schedule.every().second.do(job) schedule.run_all() ``` -------------------------------- ### Define Randomized Job Intervals Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Shows how to use the to() method to create jobs that run at random intervals between two specified time values. ```python import asyncio import aioschedule as schedule async def random_task(): print("Running at random interval") schedule.every(5).to(10).seconds.do(random_task) schedule.every(1).to(3).minutes.do(random_task) schedule.every(2).to(5).hours.do(random_task) async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Schedule Jobs Until a Specific Time (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Shows how to schedule a job to run repeatedly until a specific time. The `until()` method can accept a time string (HH:MM) or a full datetime string (YYYY-MM-DD HH:MM) to define the cutoff point for the job's execution. ```python import schedule from datetime import datetime, timedelta, time def job(): print('Boo') # run job until a 18:30 today schedule.every(1).hours.until("18:30").do(job) # run job until a 2030-01-01 18:33 today schedule.every(1).hours.until("2030-01-01 18:33").do(job) ``` -------------------------------- ### Manage Multiple Independent Schedulers Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Illustrates the creation of multiple Scheduler instances to maintain separate job queues within the same application. This allows for isolated scheduling logic for different components. ```python import asyncio import aioschedule as schedule async def foo_job(): print("Foo") async def bar_job(): print("Bar") # Create independent schedulers scheduler1 = schedule.Scheduler() scheduler2 = schedule.Scheduler() # Add jobs to different schedulers scheduler1.every().hour.do(foo_job) scheduler1.every().hour.do(bar_job) scheduler2.every(5).seconds.do(foo_job) scheduler2.every(10).seconds.do(bar_job) async def main(): while True: # Run pending jobs on each scheduler await scheduler1.run_pending() await scheduler2.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Verify scheduled job runtime Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/timezones.md Shows how to inspect the next_run attribute of a scheduled job to verify that the library correctly calculates the execution time based on the specified timezone. ```python s = every().day.at("10:30", "America/New_York").do(job) print(s.next_run) print(repr(s)) ``` -------------------------------- ### Asynchronous Job Execution and Cancellation Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/reference.md Shows how to manually trigger a job run and how to use the CancelJob exception to stop a recurring task from within the job function. ```python from aioschedule import CancelJob async def my_task(): if condition_met: return CancelJob return "Success" # Manually running a job result = await job_instance.run() ``` -------------------------------- ### Handle exceptions in job functions in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Provides guidance on how to handle exceptions thrown by job functions. This is crucial for ensuring the scheduler continues to run even if a job encounters an error. ```python import schedule def faulty_job(): raise ValueError("Something went wrong!") try: schedule.every().minute.do(faulty_job) except Exception as e: print(f"Error scheduling job: {e}") # In a real scenario, you'd likely wrap run_pending() in a try-except block ``` -------------------------------- ### Execute Pending Jobs with aioschedule Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Demonstrates how to run scheduled tasks using the run_pending method within an asynchronous loop. This ensures jobs are executed only when their scheduled time has passed. ```python import asyncio import aioschedule as schedule async def task(): print("Task executed") schedule.every(5).seconds.do(task) async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Schedule jobs with 1-second precision Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Updates the `at()` method to accept timestamps with one-second precision, allowing for more accurate scheduling of time-sensitive tasks. ```python schedule.every().day.at("10:30:05").do(job) ``` -------------------------------- ### Cancel and Clear Jobs Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Demonstrates how to remove specific jobs using cancel_job() or clear all jobs, optionally filtering by tags. ```python import asyncio import aioschedule as schedule async def task1(): print("Task 1") job1 = schedule.every().day.at("22:30").do(task1) schedule.cancel_job(job1) schedule.clear("hourly") schedule.clear() ``` -------------------------------- ### Monitor Next Run Time and Idle Duration Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Shows how to retrieve the next scheduled execution time using next_run and calculate the remaining idle time until the next job using idle_seconds(). This is useful for optimizing sleep cycles in an event loop. ```python import asyncio import aioschedule as schedule async def job(): print("Hello") schedule.every(5).seconds.do(job) async def main(): while True: # Get seconds until next job n = schedule.idle_seconds() if n is None: print("No more jobs scheduled") break elif n > 0: print(f"Sleeping for {n:.2f} seconds until next job") await asyncio.sleep(n) await schedule.run_pending() # Check next run time next_time = schedule.next_run() if next_time: print(f"Next run at: {next_time}") asyncio.run(main()) ``` -------------------------------- ### Tag and Filter Jobs Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Explains how to assign tags to jobs for easier management, filtering, and bulk operations using the tag() method. ```python import asyncio import aioschedule as schedule async def greet(name): print(f"Hello {name}") schedule.every().day.do(greet, "Andrea").tag("daily-tasks", "friend") schedule.every().hour.do(greet, "John").tag("hourly-tasks", "friend") friends = schedule.get_jobs("friend") print(f"Friend jobs: {len(friends)}") async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Schedule jobs on specific weekdays Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Introduces the ability to schedule jobs on specific days of the week, offering more granular control over job execution timing. This includes options for specific times on those days. ```python schedule.every().tuesday.do(job) schedule.every().wednesday.at("13:15").do(job) ``` -------------------------------- ### Forward arguments to job functions in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Allows arguments to be passed into the do() method, which are then forwarded to the job function at call time. This enables dynamic data passing to scheduled tasks. ```python import schedule def greet(name): print(f"Hello, {name}!") schedule.every(10).seconds.do(greet, name='Alice') ``` -------------------------------- ### Set Job Deadlines with until() Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Illustrates how to restrict the duration of a job using the until() method, which accepts various time-based inputs like strings, datetime objects, or timedeltas. ```python import asyncio import aioschedule as schedule from datetime import datetime, timedelta, time async def job(): print("Running until deadline") schedule.every(1).hours.until("18:30").do(job) schedule.every(1).hours.until("2030-01-01 18:33").do(job) schedule.every(1).hours.until(timedelta(hours=8)).do(job) schedule.every(1).hours.until(time(11, 33, 42)).do(job) schedule.every(1).hours.until(datetime(2025, 5, 17, 11, 36, 20)).do(job) async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Run jobs at a specific time every hour Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Enhances the `at_time()` functionality to allow scheduling jobs at a particular minute within every hour. This is useful for tasks that need to run at a consistent interval relative to the hour. ```python schedule.every().hour.at(':15').do(job) # Runs job 15 minutes past every hour ``` -------------------------------- ### Schedule jobs on specific weekdays in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Adds functionality to schedule jobs on specific days of the week, such as every Tuesday or Wednesday. This allows for more precise scheduling based on the day of the week. ```python import schedule def job(): print("I will run on Tuesdays") schedule.every().tuesday.do(job) schedule.every().wednesday.at("13:15").do(job) ``` -------------------------------- ### Forward arguments to job functions Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Ensures that arguments passed to the `do()` method are correctly forwarded to the job function when it is executed. This simplifies passing data to scheduled tasks. ```python def greet(name): print(f"Hello, {name}!") schedule.every().day.do(greet, name='World') ``` -------------------------------- ### Scheduler Methods Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/reference.md Methods for managing and interacting with scheduled jobs within the aioschedule library. ```APIDOC ## async run_all() ### Description Runs all scheduled jobs immediately, regardless of their scheduled time. It can be configured with a timeout and a return condition. ### Method ASYNC ### Endpoint N/A (Method within a class) ### Parameters #### Query Parameters - **delay_seconds** (int) - Optional - Delay in seconds before running jobs. - **timeout** (int | float) - Optional - Maximum seconds to wait before returning. - **return_when** (str) - Optional - Specifies when the function should return. Must be one of `FIRST_COMPLETED`, `FIRST_EXCEPTION`, or `ALL_COMPLETED`. ### Response #### Success Response (200) Returns when the specified `return_when` condition is met or timeout occurs. #### Response Example N/A (This method does not return a specific value, but controls execution flow.) ``` ```APIDOC ## get_jobs(tag: Hashable | None = None) ### Description Retrieves a list of scheduled jobs. Jobs can be filtered by a specific tag or all jobs can be returned if no tag is provided. ### Method GET ### Endpoint N/A (Method within a class) ### Parameters #### Query Parameters - **tag** (Hashable | None) - Optional - An identifier used to filter jobs by tag. ### Response #### Success Response (200) - **List[Job]** - A list of Job objects matching the criteria. #### Response Example ```json [ { "id": "job-1", "interval": 60, "unit": "seconds", "tags": ["reporting"] } ] ``` ``` ```APIDOC ## clear(tag: Hashable | None = None) ### Description Deletes scheduled jobs. Jobs can be deleted based on a specific tag, or all jobs can be deleted if no tag is provided. ### Method DELETE ### Endpoint N/A (Method within a class) ### Parameters #### Query Parameters - **tag** (Hashable | None) - Optional - An identifier used to filter jobs for deletion. ### Response #### Success Response (200) Indicates that the jobs have been cleared successfully. #### Response Example N/A (This method does not return a specific value.) ``` ```APIDOC ## cancel_job(job: Job) ### Description Cancels and removes a specific scheduled job from the scheduler. ### Method DELETE ### Endpoint N/A (Method within a class) ### Parameters #### Path Parameters - **job** (Job) - Required - The Job object to be cancelled. ### Response #### Success Response (200) Indicates that the job has been cancelled successfully. #### Response Example N/A (This method does not return a specific value.) ``` ```APIDOC ## every(interval: int = 1) ### Description Schedules a new periodic job with a specified interval. Returns an unconfigured Job object that can be further customized. ### Method POST ### Endpoint N/A (Method within a class) ### Parameters #### Query Parameters - **interval** (int) - Optional - The quantity of time units for the job's interval. Defaults to 1. ### Response #### Success Response (200) - **Job** - An unconfigured Job object. #### Response Example ```json { "id": "unconfigured-job-1", "interval": 5, "unit": "minutes" } ``` ``` ```APIDOC ## get_next_run(tag: Hashable | None = None) ### Description Retrieves the datetime of the next scheduled job run. Can filter by a specific tag. ### Method GET ### Endpoint N/A (Method within a class) ### Parameters #### Query Parameters - **tag** (Hashable | None) - Optional - An identifier to filter the next run time for jobs with this tag. ### Response #### Success Response (200) - **datetime | None** - The datetime of the next scheduled run, or None if no jobs are scheduled. #### Response Example ```json "2023-10-27T10:00:00Z" ``` ``` -------------------------------- ### Implement Graceful Exception Handling Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Provides a decorator pattern to catch exceptions during job execution. This prevents individual job failures from crashing the entire scheduler and allows for optional job cancellation on failure. ```python import asyncio import functools import traceback import aioschedule as schedule def catch_exceptions(cancel_on_failure=False): def decorator(job_func): @functools.wraps(job_func) async def wrapper(*args, **kwargs): try: return await job_func(*args, **kwargs) except Exception: print(traceback.format_exc()) if cancel_on_failure: return schedule.CancelJob return wrapper return decorator @catch_exceptions(cancel_on_failure=True) async def risky_task(): # This will fail but won't crash the scheduler return 1 / 0 @catch_exceptions(cancel_on_failure=False) async def retry_task(): # This will fail but keep retrying raise ValueError("Temporary error") schedule.every(5).seconds.do(risky_task) schedule.every(10).seconds.do(retry_task) async def main(): while True: await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Schedule jobs at a specific time in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Enhances the scheduling capabilities by allowing jobs to be run at a particular time every hour or day. This includes precise time specifications like HH:MM:SS. ```python import schedule def job(): print("I run at 15 minutes past the hour") schedule.every().hour.at(":15").do(job) schedule.every().day.at("10:30:00").do(job) ``` -------------------------------- ### Enable Debug Logging for Schedule Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/logging.md Configures the standard Python logging library to capture DEBUG level messages from the 'schedule' logger. This is useful for monitoring job execution cycles and internal scheduling events. ```python import schedule import logging logging.basicConfig() schedule_logger = logging.getLogger('schedule') schedule_logger.setLevel(level=logging.DEBUG) def job(): print("Hello, Logs") schedule.every().second.do(job) schedule.run_all() schedule.clear() ``` -------------------------------- ### Execute jobs until a condition is met in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Implements the .until() method for jobs, allowing them to execute until a specified condition is met. This is useful for jobs that need to run for a limited duration or until a certain state is achieved. ```python import schedule import time def my_job(): print("I'm working...") schedule.every(10).seconds.until("2023-12-31 23:59:59").do(my_job) while True: schedule.run_pending() time.sleep(1) ``` -------------------------------- ### Implement Self-Canceling Jobs Source: https://context7.com/geoff-carve-systems/python-aioschedule/llms.txt Shows how to return the CancelJob constant from a job function to automatically remove it from the scheduler after execution. ```python import asyncio import aioschedule as schedule async def run_once(): print("This runs only once") return schedule.CancelJob schedule.every().day.at("22:30").do(run_once) async def main(): while schedule.get_jobs(): await schedule.run_pending() await asyncio.sleep(1) asyncio.run(main()) ``` -------------------------------- ### Tag jobs and cancel by tag Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Adds the capability to tag jobs for easier identification and management. It also introduces the ability to cancel jobs based on their assigned tags. ```python job = schedule.every().day.do(my_job).tag('daily_report') schedule.cancel_job_by_tag('daily_report') ``` -------------------------------- ### Filter and Cancel Jobs by Tags (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Shows how to cancel multiple jobs at once by filtering them using tags. The `schedule.clear(tag)` method removes all jobs associated with a given tag, providing a convenient way to manage groups of tasks. ```python import schedule def greet(name): print('Hello {}'.format(name)) schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend') schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend') schedule.every().hour.do(greet, 'Monica').tag('hourly-tasks', 'customer') schedule.every().day.do(greet, 'Derek').tag('daily-tasks', 'guest') schedule.clear('daily-tasks') # Will prevent every job tagged as `daily-tasks` from running again. ``` -------------------------------- ### Force Execution of All Jobs Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md The run_all() method triggers every scheduled job immediately, regardless of their original schedule. An optional delay_seconds argument can be provided to introduce a pause between each job execution. ```python import schedule def job_1(): print('Foo') def job_2(): print('Bar') schedule.every().monday.at("12:40").do(job_1) schedule.every().tuesday.at("16:40").do(job_2) # Run all immediately schedule.run_all() # Run all with a 10 second delay schedule.run_all(delay_seconds=10) ``` -------------------------------- ### Job Scheduling API Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/README.rst Methods for defining and running periodic asynchronous jobs using the aioschedule library. ```APIDOC ## Scheduling Jobs ### Description Defines periodic tasks to be executed asynchronously at specified intervals or times. ### Method N/A (Library Method) ### Parameters - **interval** (int) - Required - The frequency of the job. - **unit** (string) - Required - The time unit (seconds, minutes, hours, days). - **job_func** (callable) - Required - The asynchronous function to execute. ### Request Example ```python import aioschedule as schedule async def job(): print("Task running") # Schedule every 1 second schedule.every(1).seconds.do(job) # Schedule at a specific time schedule.every().day.at("10:30").do(job) ``` ### Execution #### Success Response - **status** (boolean) - Returns True when the pending jobs are processed successfully. ### Response Example ```python loop = asyncio.get_event_loop() while True: loop.run_until_complete(schedule.run_pending()) ``` ``` -------------------------------- ### Filter jobs by tags using get_jobs() Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Enhances the get_jobs() function to support filtering scheduled jobs by tags. This allows for easier retrieval and management of specific job groups. ```python jobs = schedule.get_jobs('tag_name') ``` -------------------------------- ### Handle job exceptions Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Provides guidance and potentially mechanisms for handling exceptions raised by job functions. This ensures that scheduler stability is maintained even when individual jobs encounter errors. ```python # Example of handling exceptions within a job def job_with_exception(): try: # ... code that might raise an exception ... pass except Exception as e: print(f"Job failed: {e}") # Optionally return schedule.CancelJob here if the job should stop after failing ``` -------------------------------- ### Add @repeat() decorator Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Introduces the @repeat() decorator, allowing jobs to be scheduled for repeated execution. This enhances flexibility in defining recurring tasks within the scheduler. ```python from aioschedule import repeat @repeat(seconds=10) def my_job(): print("This job repeats every 10 seconds.") ``` -------------------------------- ### Cancel All Scheduled Jobs (Python) Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/examples.md Demonstrates how to remove all scheduled jobs from the scheduler using the `schedule.clear()` method. This is useful for resetting the scheduler or stopping all pending tasks. ```python import schedule def greet(name): print('Hello {}'.format(name)) schedule.every().second.do(greet) schedule.clear() ``` -------------------------------- ### Add @repeat() decorator in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Introduces the @repeat() decorator for scheduling recurring jobs. This decorator allows for more flexible job scheduling by specifying repeat intervals. ```python from aioschedule import repeat @repeat(seconds=10) def job(): print("I work every 10 seconds") ``` -------------------------------- ### Filter jobs by tag in Python Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/HISTORY.rst Enables filtering scheduled jobs by tags using the get_jobs() method. This feature simplifies managing and retrieving specific jobs from a collection based on assigned tags. ```python import schedule def my_job(): print("This is a tagged job") schedule.every().day.do(my_job).tag('important', 'daily') tagged_jobs = schedule.get_jobs('important') print(tagged_jobs) ``` -------------------------------- ### Add execute .until() method Source: https://github.com/geoff-carve-systems/python-aioschedule/blob/master/docs/changelog.md Adds the .until() method to jobs, enabling the specification of an end condition for their execution. This allows jobs to run up to a certain point or for a limited duration. ```python from datetime import datetime, timedelta async def my_job(): print("This job runs until a specific time.") schedule.every(5).seconds.until(datetime.now() + timedelta(minutes=1)).do(my_job) ```