You can download this code by clicking the button below.
This code is now available for download.
This code defines a function named `schedule_random_number` that uses the APScheduler library to schedule the `generate_random_number` function, which randomly generates a number between 1 and 100, to be executed every 1 minute. The code uses `BackgroundScheduler` to run the scheduled task in the background.
Technology Stack : APScheduler, random
Code Type : Timed task
Code Difficulty : Intermediate
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import random
def generate_random_number():
return random.randint(1, 100)
def schedule_random_number():
scheduler = BackgroundScheduler()
scheduler.add_job(generate_random_number, 'interval', minutes=1)
scheduler.start()
print(f"Scheduler started at {datetime.now()}")
try:
# To keep the main thread alive
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()