Random Number Check Scheduler with APScheduler

  • Share this:

Code introduction


This code defines a function named random_task that generates a random number between 1 and 10 and checks if the number is even or odd. It then sets up a scheduling job using the APScheduler library to execute the random_task function every 5 seconds. The code runs continuously until the user interrupts it with a keyboard command.


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():
    # Generate a random number between 1 and 10
    random_number = random.randint(1, 10)
    
    # Check if the random number is even or odd
    if random_number % 2 == 0:
        print("The number is even.")
    else:
        print("The number is odd.")

# Scheduler setup
scheduler = BackgroundScheduler()
scheduler.add_job(random_task, 'interval', seconds=5)
scheduler.start()

# To demonstrate that the scheduler is running, we'll sleep for a while
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    # Stop the scheduler on keyboard interrupt
    scheduler.shutdown()