Code introduction
This code defines a function named generate_random_task that uses the APScheduler library to create a background scheduled task. The task is set to execute after a random delay and will print the current time upon execution.
Technology Stack : The code uses the APScheduler library and the datetime, random, and time modules. The APScheduler library is used for scheduling tasks, datetime is used to get the current time, random is used to generate a random delay, and time is used to keep the main thread alive.
Code Type : The type of code
Code Difficulty :
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import random
def generate_random_task():
# This function generates a random task with a delay and executes it using APScheduler
def task():
print(f"Task executed at {datetime.now()}")
delay = random.randint(1, 5) # Random delay between 1 to 5 seconds
scheduler = BackgroundScheduler()
scheduler.add_job(task, 'interval', seconds=delay)
scheduler.start()
try:
# Keep the main thread alive
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()