Scheduling Random Number Check with APScheduler

  • Share this:

Code introduction


This code uses the APScheduler library to create a background scheduled task that runs the random_task function every 5 seconds. The random_task function generates a random number between 1 and 10 and determines if the number is even or odd, then prints the corresponding message.


Technology Stack : APScheduler, random, time

Code Type : Timed task

Code Difficulty : Intermediate


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

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

def run_scheduler():
    # Create a BackgroundScheduler object
    scheduler = BackgroundScheduler()
    
    # Add the random_task function to the scheduler to run every 5 seconds
    scheduler.add_job(random_task, 'interval', seconds=5)
    
    # Start the scheduler
    scheduler.start()
    
    # Keep the script running
    try:
        # To keep the main thread alive
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        # Stop the scheduler when the script is stopped
        scheduler.shutdown()