gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Write Python script which executes scheduled tasks. It imports config file tasks.py…
- User
Write Python script which executes scheduled tasks. It imports config file tasks.py every minute. Tasks.py has next syntax: one task per line. Every line looks like "command":"when_to_run" "when_to_run" can be "autorun", that means task runs once at master script starts. "when_to_run" also can be pattern like "5m" (minutes), "10s", "1h" (hours), "3d" (days), "7w" (weeks), "1M" (months) and "2Y" (years). It means how often task must be runned
- Assistant
To achieve the required functionality, we need to perform the following steps:
- Import and read the configuration file
tasks.py. - Parse each task and its associated schedule.
- Execute tasks based on their schedule.
- Use appropriate functions/methods to maintain the scheduling of tasks (e.g., running a task every minute, every hour, etc.).
Below is the implementation of the script:
tasks.py (must be placed in the same directory as the script)
tasks = { "task1": "autorun", "task2": "5m", "task3": "10s", "task4": "1h", "task5": "3d", "task6": "7w", "task7": "1M", "task8": "2Y" }master_script.py
import importlib import threading import time from datetime import datetime, timedelta from typing import Dict, Any # Global variables to keep track of last run time for tasks last_run_times = {} def import_tasks() -> Dict[str, str]: # Dynamically import tasks module tasks_module = importlib.import_module('tasks') importlib.reload(tasks_module) # Reload module to get any updated tasks return tasks_module.tasks def parse_interval(interval: str) -> timedelta: """ Convert interval string like '5m', '10s', '1h', '3d', '7w', '1M', '2Y' to timedelta. """ amount = int(interval[:-1]) unit = interval[-1].lower() if unit == 's': return timedelta(seconds=amount) elif unit == 'm': return timedelta(minutes=amount) elif unit == 'h': return timedelta(hours=amount) elif unit == 'd': return timedelta(days=amount) elif unit == 'w': return timedelta(weeks=amount) elif unit == 'm': # Assuming 'm' in "1M" stands for months days_in_month = 30 # Simplified month duration return timedelta(days=amount * days_in_month) elif unit == 'y': days_in_year = 365 # Simplified year duration return timedelta(days=amount * days_in_year) else: raise ValueError(f"Unsupported interval format: {interval}") def execute_command(command: str): print(f"Executing {command} at {datetime.now()}") def scheduler(task_name: str, interval: str): while True: now = datetime.now() if interval == "autorun": if task_name not in last_run_times: execute_command(task_name) last_run_times[task_name] = now return if task_name in last_run_times: if now - last_run_times[task_name] >= parse_interval(interval): execute_command(task_name) last_run_times[task_name] = now else: execute_command(task_name) last_run_times[task_name] = now time.sleep(1) # Check every second def main(): tasks = import_tasks() for task_name, interval in tasks.items(): t = threading.Thread(target=scheduler, args=(task_name, interval)) t.daemon = True t.start() while True: time.sleep(60) # Re-import tasks every minute tasks = import_tasks() if __name__ == "__main__": main()Explanation:
- Importing and Parsing tasks.py: The
import_tasksfunction dynamically imports and reloads thetasks.pyfile to get the latest tasks. - Parsing Intervals: The
parse_intervalfunction converts strings like "5m", "10s", etc., intotimedeltaobjects. - Scheduling Tasks: The
schedulerfunction handles the execution of each task at their scheduled time. It checks every second whether the task needs to be run. - Threading: Each task is run in a separate thread to allow for concurrent execution.
- Re-importing tasks: The main loop in
mainre-imports the tasks every minute to check for any updates in thetasks.pyfile.
Make sure
tasks.pyand themaster_script.pyare in the same directory before running the script. Adjust thetasks.pyfile according to your actual tasks. - Import and read the configuration file