Grok 4.1 Fast· xai
Frontier Reasoning Traces
Develop a Python program to schedule and run periodic tasks using APScheduler.
- User
Develop a Python program to schedule and run periodic tasks using APScheduler.
- Assistant
""" A simple Python program demonstrating APScheduler for scheduling periodic tasks. Requirements: - Install APScheduler: pip install apscheduler This program schedules three periodic tasks: 1. A job that prints "Hello World!" every 10 seconds. 2. A job that prints the current time every 30 seconds. 3. A job that prints a counter every minute. The scheduler runs in the background. Press Ctrl+C to stop gracefully. """ from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.interval import IntervalTrigger import time import signal import sys import datetime # Global counter for demonstration counter = 0 def job_hello(): """Periodic job: Prints 'Hello World!' every 10 seconds.""" print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Hello World!") def job_time(): """Periodic job: Prints current time every 30 seconds.""" print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Current time task executed.") def job_counter(): """Periodic job: Prints and increments a counter every 60 seconds.""" global counter counter += 1 print(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Counter job: {counter}") def signal_handler(sig, frame): """Graceful shutdown on Ctrl+C.""" print("\nShutting down scheduler...") scheduler.shutdown() sys.exit(0) # Set up signal handler for graceful shutdown signal.signal(signal.SIGINT, signal_handler) # Create a background scheduler scheduler = BackgroundScheduler() # Add periodic jobs using IntervalTrigger scheduler.add_job( job_hello, trigger=IntervalTrigger(seconds=10), id='hello_job', name='Hello World Job', replace_existing=True ) scheduler.add_job( job_time, trigger=IntervalTrigger(seconds=30), id='time_job', name='Current Time Job', replace_existing=True ) scheduler.add_job( job_counter, trigger=IntervalTrigger(seconds=60), id='counter_job', name='Counter Job', replace_existing=True ) # Start the scheduler scheduler.start() print("Scheduler started. Jobs are running in the background.") print("Press Ctrl+C to stop.") try: # Keep the main thread alive while True: time.sleep(1) except KeyboardInterrupt: # This is handled by the signal handler, but for completeness passHow to Run:
- Save the code to a file, e.g.,
scheduler_demo.py. - Install APScheduler:
pip install apscheduler. - Run:
python scheduler_demo.py. - Observe the periodic outputs in the console.
- Press
Ctrl+Cto stop.
Key Features Demonstrated:
- BackgroundScheduler: Runs jobs without blocking the main thread.
- IntervalTrigger: For fixed intervals (seconds, minutes, etc.).
- Job IDs and Names: For easy management (e.g., pausing/resuming).
- Graceful Shutdown: Handles
Ctrl+Ccleanly. - Logging with Timestamps: Easy to verify execution timing.
You can extend this by adding more triggers (e.g.,
CronTriggerfor cron-like scheduling), storing jobs in a database, or integrating with web frameworks like Flask/FastAPI. Let me know if you need modifications! - Save the code to a file, e.g.,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.