In python I have an app that need to run 3 different functions (functionA(),…
- User
In python I have an app that need to run 3 different functions (functionA(), functionBeta(), functionTrzecia()) one after another, but only if spis[‘functionName’][
last_accessed] value from the file spis.json is older than set amount of hours.What are the best practices for a simple setup that checks and runs the functions, and after running updates th last accesses value?
Assistant
Of course! This is a classic task that benefits from a clean, robust, and readable setup. Here are the best practices for a simple yet effective solution, followed by a complete Python code example.
Best Practices for This Setup
-
Separate Configuration from Logic: Don't hardcode file paths or time thresholds directly in your main logic. Use constants at the top of your script. This makes it easy to change them later.
-
Use a Data-Driven Approach: Instead of a long
if/elif/elsechain, use a dictionary to map function names (as strings) to the actual function objects. This makes your code more scalable and easier to read. If you add afunctionDelta(), you only need to add it to the dictionary, not change the core loop. -
Handle Timezones Correctly: Always use timezone-aware datetimes, preferably UTC (
timezone.utc). This prevents bugs related to daylight saving time or running the script on servers in different timezones. Store timestamps in a standard format like ISO 8601, which is both human-readable and machine-parsable. -
Robust File Handling:
- Always use a
with open(...)block to ensure files are closed correctly, even if errors occur. - Handle the case where the
spis.jsonfile or a specific function's entry doesn't exist yet. The script should be able to create the file or add a new entry on its first run. - Only write to the file when a change has actually been made. This avoids unnecessary disk I/O.
- Always use a
-
Error Handling: If one of your functions (
functionA, etc.) fails with an exception, you should not update itslast_accessedtimestamp. The task didn't complete, so it should be attempted again on the next run. Use atry...exceptblock around the function call. -
Code Organization: Encapsulate the logic in a main "runner" function. Use the standard
if __name__ == "__main__":block to make your script both runnable and importable.
Complete Python Solution
Here is a full example that implements all the best practices described above.
1. The Python Script (
app.py)import json from datetime import datetime, timedelta, timezone from pathlib import Path import time # For simulating work # --- 1. Configuration --- # Use constants for easy modification HOURS_THRESHOLD = 24 SPIS_FILE = Path("spis.json") # --- 2. Your Core Functions --- # These are the functions you want to run on a schedule. # We'll add some print statements and a sleep to simulate work. def functionA(): """Performs the first critical task.""" print("-> Running functionA: Performing data aggregation...") time.sleep(2) # Simulate work print("-> functionA: Task complete.") def functionBeta(): """Performs the second critical task.""" print("-> Running functionBeta: Generating daily report...") time.sleep(3) # Simulate work # To demonstrate error handling, let's make this one fail sometimes. if datetime.now().minute % 2 == 0: # Fails on even minutes raise ConnectionError("Failed to connect to the reporting database.") print("-> functionBeta: Task complete.") def functionTrzecia(): """Performs the third critical task.""" print("-> Running functionTrzecia: Cleaning up temporary files...") time.sleep(1) # Simulate work print("-> functionTrzecia: Task complete.") # --- 3. Helper Functions for File and Time Logic --- def load_or_initialize_spis() -> dict: """ Loads the state from the JSON file. If the file doesn't exist, it returns a default empty structure. """ if not SPIS_FILE.exists(): print(f"'{SPIS_FILE}' not found. A new one will be created.") return {} with open(SPIS_FILE, "r") as f: try: return json.load(f) except json.JSONDecodeError: print(f"Warning: Could not decode JSON from '{SPIS_FILE}'. Starting fresh.") return {} # Return empty dict if file is corrupt def save_spis(data: dict): """Saves the given data to the JSON file with nice formatting.""" with open(SPIS_FILE, "w") as f: json.dump(data, f, indent=4) print(f"State updated and saved to '{SPIS_FILE}'.") # --- 4. The Main Runner Logic --- def run_scheduled_functions(): """ Checks the last accessed time for each function and runs it if the threshold has been exceeded. """ print("\n--- Starting scheduled function check ---") # Data-driven approach: Map string names to function objects. # This is the single place to add/remove functions. tasks = { 'functionA': functionA, 'functionBeta': functionBeta, 'functionTrzecia': functionTrzecia } spis = load_or_initialize_spis() data_was_changed = False now_utc = datetime.now(timezone.utc) for name, func in tasks.items(): # Get the record for this function, defaulting if not found task_record = spis.get(name, {}) last_accessed_str = task_record.get('last_accessed') should_run = False if not last_accessed_str: print(f"'{name}' has no 'last_accessed' time. Running for the first time.") should_run = True else: try: last_accessed_utc = datetime.fromisoformat(last_accessed_str) time_since_last_run = now_utc - last_accessed_utc if time_since_last_run > timedelta(hours=HOURS_THRESHOLD): print(f"'{name}' was last run {time_since_last_run}. It's time to run again.") should_run = True else: print(f"'{name}' was run recently ({time_since_last_run} ago). Skipping.") except ValueError: print(f"Warning: Invalid timestamp format for '{name}'. Running it.") should_run = True if should_run: try: # Run the actual function func() # IMPORTANT: Only update the timestamp on success print(f"Successfully ran '{name}'. Updating timestamp.") # Ensure the nested dictionary exists if name not in spis: spis[name] = {} spis[name]['last_accessed'] = now_utc.isoformat() data_was_changed = True except Exception as e: # Best Practice: If the function fails, DO NOT update the timestamp. # It will be retried on the next execution of the script. print(f"[ERROR] An exception occurred while running '{name}': {e}") print(f"Timestamp for '{name}' will NOT be updated. It will be retried later.") print("-" * 20) if data_was_changed: save_spis(spis) else: print("No functions needed to be run. No changes saved.") print("--- Scheduled function check complete ---\n") # --- 5. Script Entry Point --- if __name__ == "__main__": run_scheduled_functions()2. The JSON File (
spis.json)When you run the script for the first time, this file will be created. After a successful run, it will look something like this:
{ "functionA": { "last_accessed": "2023-10-27T14:45:01.123456+00:00" }, "functionTrzecia": { "last_accessed": "2023-10-27T14:45:05.123456+00:00" } }(Notice
functionBetamight be missing if it failed to run).How to Use
- Save the code as
app.py. - Run it from your terminal:
python app.py. - The first time, all functions will run. A
spis.jsonfile will be created. - Run it again immediately. The script will see the recent timestamps and skip all functions.
- To test, you can either:
- Change
HOURS_THRESHOLDto a very small number (e.g.,0.001). - Manually edit the timestamps in
spis.jsonto be an old date (e.g., change2023-10-27to2022-10-26).
- Change
This setup is simple, robust, and easy to maintain, making it a great starting point for your application.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.