Background Scheduler for Random Fruit Selection

  • Share this:

Code introduction


This function creates a background scheduler that randomly selects and prints a fruit name every 10 seconds.


Technology Stack : APScheduler, random, time

Code Type : The type of code

Code Difficulty : Intermediate


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

def random_task():
    # This function will randomly pick an item from a list and print it
    items = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
    picked_item = random.choice(items)
    print(f"Picked fruit: {picked_item}")

def run_scheduler():
    # This function sets up a scheduler to run the random_task every 10 seconds
    scheduler = BackgroundScheduler()
    scheduler.add_job(random_task, 'interval', seconds=10)
    scheduler.start()
    try:
        # To keep the main thread alive
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()

def xxx():
    run_scheduler()

# JSON representation of the code