Random Task Scheduler with APScheduler

  • Share this:

Code introduction


This code defines a custom function named xxx that uses the APScheduler library to create a background scheduler, randomly selects an integer as the job delay, and then executes a random task that decides whether to sleep or print a message based on whether the random number is odd or even.


Technology Stack : The code uses the APScheduler library and Python's time module.

Code Type : The type of code

Code Difficulty :


                
                    
from apscheduler.schedulers.background import BackgroundScheduler
import random
import time

def random_task():
    # Randomly select an integer between 1 and 10
    number = random.randint(1, 10)
    # If the number is even, sleep for the number of seconds
    if number % 2 == 0:
        time.sleep(number)
        print(f"Number {number} is even, slept for {number} seconds.")
    # If the number is odd, print a message
    else:
        print(f"Number {number} is odd.")

def xxx():
    # Initialize the scheduler
    scheduler = BackgroundScheduler()
    # Add the random_task function to the scheduler with a random delay
    scheduler.add_job(random_task, 'interval', seconds=random.randint(1, 10))
    # Start the scheduler
    scheduler.start()
    # Keep the script running
    try:
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Stop the scheduler when the script is interrupted
        scheduler.shutdown()