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 that uses APScheduler's ThreadPoolExecutor and BackgroundScheduler to generate and print a random number every 10 seconds.
Technology Stack : APScheduler, ThreadPoolExecutor, ProcessPoolExecutor, BackgroundScheduler, random
Code Type : Timed task
Code Difficulty : Intermediate
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler
def random_task():
# This function demonstrates the use of ThreadPoolExecutor and BackgroundScheduler from APScheduler.
def generate_random_number():
import random
return random.randint(1, 100)
with ThreadPoolExecutor(max_workers=5) as executor:
result = executor.submit(generate_random_number)
print(f"Random number generated: {result.get()}")
# Scheduler configuration
scheduler = BackgroundScheduler()
# Schedule the random_task function to run every 10 seconds
scheduler.add_job(random_task, 'interval', seconds=10)
# Start the scheduler
scheduler.start()
# To keep the main thread alive
try:
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()