Background Scheduler with Random Operations

  • Share this:

Code introduction


This code uses the APScheduler library to create a background scheduled task that runs the random_task function every minute. The random_task function randomly performs addition, subtraction, multiplication, or division operations and prints the result.


Technology Stack : APScheduler, datetime, random

Code Type : Timed task

Code Difficulty : Intermediate


                
                    
from apscheduler.schedulers.background import BackgroundScheduler
import random

def random_task():
    # This function simulates a background task that performs a random operation every minute.
    print(f"Task executed at {datetime.now()} with random operation {random.choice(['add', 'subtract', 'multiply', 'divide'])}")

# Define the scheduler
scheduler = BackgroundScheduler()

# Schedule the random_task function to run every minute
scheduler.add_job(random_task, 'interval', minutes=1)

# Start the scheduler
scheduler.start()

# To keep the main thread alive
try:
    # This is to keep the main thread alive
    while True:
        time.sleep(2)
except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()