You can download this code by clicking the button below.
This code is now available for download.
This code defines a function named random_task, which will be executed by the APScheduler scheduler every 10 seconds. The code also includes the logic for initializing the scheduler, scheduling the task, and starting and stopping the scheduler.
Technology Stack : APScheduler, BackgroundScheduler, IntervalTrigger, datetime
Code Type : Timed task
Code Difficulty : Intermediate
import random
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from datetime import datetime
def random_task():
# This function will be executed by the scheduler every 10 seconds
print(f"Task executed at {datetime.now()}")
# Initialize the scheduler
scheduler = BackgroundScheduler()
# Schedule the random_task to run every 10 seconds
scheduler.add_job(random_task, trigger=IntervalTrigger(seconds=10))
# Start the scheduler
scheduler.start()
# Keep the script running
try:
while True:
pass
except (KeyboardInterrupt, SystemExit):
# Stop the scheduler when the script is stopped
scheduler.shutdown()