Skip to content
The Chat Archive
chatgpt-4o-latest-20250326· OpenAI LMArena Human Preference 140K

In python I have an app that need to run 3 different functions (functionA(),…

  1. 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?

  2. Assistant

    To set up your Python app so that it runs specific functions only if they haven't been accessed recently, you can follow these best practices, especially when managing this kind of state using a JSON file (spis.json).


    ✅ Problem Summary

    You have:

    • Three functions: functionA(), functionBeta(), functionTrzecia()
    • A file spis.json, storing last_accessed datetime for each function.
    • A time threshold (e.g., 2 hours). If a function hasn't been run in over 2 hours, it should run and update the last_accessed.

    ✅ Best Practice Setup

    ✅ 1. Structure of spis.json file

    Your file should look something like this:

    {
      "functionA": {
        "last_accessed": "2025-06-04T12:30:00"
      },
      "functionBeta": {
        "last_accessed": "2025-06-05T02:00:00"
      },
      "functionTrzecia": {
        "last_accessed": "2025-06-05T05:45:00"
      }
    }
    

    Timestamps are stored in ISO 8601 format (standard & parsable).


    ✅ 2. Define a Utility to Load and Save the JSON File

    import json
    from datetime import datetime, timedelta
    from pathlib import Path
    
    SPIS_PATH = Path('spis.json')
    
    def load_spis():
        if not SPIS_PATH.exists():
            return {}
        with open(SPIS_PATH, 'r') as f:
            return json.load(f)
    
    def save_spis(spis):
        with open(SPIS_PATH, 'w') as f:
            json.dump(spis, f, indent=2)
    

    ✅ 3. Define a Wrapper to Check and Run Function with Time Threshold

    def run_if_due(func, spis, hours_threshold):
        name = func.__name__  # Get function name to match with spis key
        now = datetime.utcnow()
    
        # Get last accessed time from spis or fallback
        last_accessed_str = spis.get(name, {}).get('last_accessed')
        if last_accessed_str:
            last_accessed = datetime.fromisoformat(last_accessed_str)
        else:
            last_accessed = datetime.min  # Force run if never accessed
    
        # Check threshold
        if now - last_accessed > timedelta(hours=hours_threshold):
            print(f"Running {name}...")
            func()
            # Update timestamp
            spis[name] = {'last_accessed': now.isoformat()}
        else:
            print(f"Skipping {name}: Last run {last_accessed}, less than {hours_threshold} hours ago.")
    

    ✅ 4. Your Main Logic

    def functionA():
        print("Executing A")
    
    def functionBeta():
        print("Executing Beta")
    
    def functionTrzecia():
        print("Executing Trzecia")
    
    def main():
        HOURS_THRESHOLD = 2  # You can change this as needed
    
        spis = load_spis()
    
        for func in [functionA, functionBeta, functionTrzecia]:
            run_if_due(func, spis, HOURS_THRESHOLD)
    
        save_spis(spis)
    
    if __name__ == "__main__":
        main()
    

    ✅ Features and Best Practices Used:

    • ✅ Readable, ISO date format stored in file
    • ✅ UTC time for consistency across environments
    • ✅ Default to running function if no timestamp exists
    • ✅ Safe file operations (handle missing file)
    • ✅ Modular utilities: easy to test and reuse
    • ✅ Separation of concerns: logic for scheduling vs function work

    🔒 Optional Enhancements (for production apps):

    • Add file lock to prevent race conditions if multiple processes may run the app.
    • Handle exceptions around reading/writing the file robustly.
    • Log function runs to file or external system if required.

    Let me know if you want to:

    • Use async functions
    • Store this state in a database
    • Add unit tests for this behavior

    I'm happy to expand!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.