Random Task Scheduler with APScheduler

  • Share this:

Code introduction


The code defines a function named random_task, which randomly selects a task from a predefined list to execute. It also uses the APScheduler library to create a background task scheduler that executes the random_task function every 5 seconds.


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():
    # Select a random task from the list
    tasks = ['task1', 'task2', 'task3']
    selected_task = random.choice(tasks)
    
    # Simulate different tasks
    if selected_task == 'task1':
        print("Performing task 1...")
        time.sleep(2)
    elif selected_task == 'task2':
        print("Performing task 2...")
        time.sleep(3)
    else:
        print("Performing task 3...")
        time.sleep(4)

def schedule_random_task():
    # Create a background scheduler
    scheduler = BackgroundScheduler()
    
    # Schedule the random task every 5 seconds
    scheduler.add_job(random_task, 'interval', seconds=5)
    
    # Start the scheduler
    scheduler.start()
    
    # Keep the main thread alive
    try:
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()