Randomly Scheduled Task with APScheduler

  • Share this:

Code introduction


The code defines a function named random_task that uses the APScheduler library to schedule itself. Each time the function is called, it randomly selects a time between 1 to 5 minutes from now to execute itself.


Technology Stack : The code defines a function named random_task that uses the APScheduler library to schedule itself. Each time the function is called, it randomly selects a time between 1 to 5 minutes from now to execute itself.

Code Type : Timed task

Code Difficulty : Intermediate


                
                    
import random
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta

def random_task():
    # This function is scheduled to run randomly between 1 and 5 minutes from now.
    scheduler = BackgroundScheduler()
    now = datetime.now()
    random_seconds = random.randint(60, 300)
    scheduled_time = now + timedelta(seconds=random_seconds)
    scheduler.add_job(random_task, 'date', run_date=scheduled_time)
    scheduler.start()
    print(f"Task scheduled to run at {scheduled_time}")