Random Number Selection and Scheduling with APScheduler

  • Share this:

Code introduction


This code defines a function `random_task` that randomly selects a number and prints it. The `schedule_random_task` function uses the APScheduler library to schedule the execution of `random_task` at a random interval between 1 to 10 seconds.


Technology Stack : APScheduler, random, time

Code Type : Timed task scheduling

Code Difficulty : Intermediate


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

def random_task():
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    selected_number = random.choice(numbers)
    print(f"Selected number: {selected_number}")

def schedule_random_task():
    scheduler = BackgroundScheduler()
    scheduler.add_job(random_task, 'interval', seconds=random.randint(1, 10))
    scheduler.start()
    try:
        # To keep the main thread alive
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()