Creating a Background Scheduler with APScheduler for Hourly Tasks

  • Share this:

Code introduction


The code defines a custom function named xxx that uses the APScheduler library to create a background scheduler for scheduling tasks. It adds a job to the scheduler that runs the random_task function every hour and allows the scheduler to run for 2 hours.


Technology Stack : APScheduler, datetime

Code Type : Timed task

Code Difficulty : Intermediate


                
                    
import random
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta

def random_task():
    # This function simulates a random task that triggers every hour
    print(f"Task executed at {datetime.now()}")

def xxx(arg1, arg2):
    # Create a scheduler instance
    scheduler = BackgroundScheduler()
    
    # Add a job that will run every hour
    scheduler.add_job(random_task, 'interval', hours=1)
    
    # Start the scheduler
    scheduler.start()
    
    # Let the scheduler run for 2 hours
    try:
        # To simulate a long running process, we will just sleep for 2 hours
        time.sleep(2 * 3600)
    except (KeyboardInterrupt, SystemExit):
        # Stop the scheduler when the script is stopped
        scheduler.shutdown()