Randomly Scheduled Time Printing Task with APScheduler

  • Share this:

Code introduction


This function uses the APScheduler library to create a scheduled task that triggers randomly between 1 to 10 seconds, printing the current date and time.


Technology Stack : APScheduler

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
from apscheduler.schedulers.blocking import BlockingScheduler
import random
import datetime

def random_task():
    # This function is triggered by the scheduler and prints a random date and time
    now = datetime.datetime.now()
    print(f"Task triggered at {now.strftime('%Y-%m-%d %H:%M:%S')}")

def xxx():
    # Scheduler initialization
    scheduler = BlockingScheduler()

    # Adding the random_task function to the scheduler with a random interval
    interval = random.randint(1, 10)  # Random interval between 1 and 10 seconds
    scheduler.add_job(random_task, 'interval', seconds=interval)

    # Start the scheduler
    scheduler.start()

# JSON representation of the code                
              
Tags: