demo.py

Overview

This script serves as a practical demonstration of two primary functionalities within the system:

  1. Task Timing: Utilizing the TaskTimer class from the Precise Task Timing module to measure elapsed time for a short, simulated task with millisecond precision.

  2. Scheduled Task Execution: Leveraging the next_run function from the Next Run Calculation module to compute the next scheduled datetime for a cron-like expression starting from a specified reference time.

The demo script showcases how these two independent modules—timing and scheduling—can be combined in a simple Python script to measure execution duration and calculate future task run times based on cron schedules.


Detailed Breakdown

Imports

Main Execution Block

The script executes its demonstrations only when run as the main module (if __name__ == "__main__":), making it suitable for direct script execution without affecting imports elsewhere.


Timing Demonstration

t = TaskTimer().start()
import time; time.sleep(0.05)
t.stop()
print(f"Elapsed: {t.elapsed_ms} ms")

Scheduling Demonstration

nr = next_run("0 9 * * *", since=datetime(2025, 10, 2, 8, 59))
print("Next run at 9:00 daily from 08:59 ->", nr)

Interaction with Other Modules


Important Implementation Details


Usage Examples

Measuring Execution Time

from tasktimer import TaskTimer
import time

timer = TaskTimer().start()
# Simulated task
time.sleep(0.1)
timer.stop()
print(f"Elapsed time: {timer.elapsed_ms} ms")

Calculating Next Scheduled Run

from tasktimer.schedule import next_run
from datetime import datetime

cron_expr = "15 14 * * 1-5"  # 2:15 PM on weekdays
reference_time = datetime.now()
next_run_time = next_run(cron_expr, since=reference_time)
print("Next scheduled run:", next_run_time)

Visual Diagram

flowchart TD
Start["Script start (if __main__)"]
Start --> TimerDemo["TaskTimer demo"]
TimerDemo --> CreateTimer["Create TaskTimer and start"]
CreateTimer --> Sleep["Sleep for 50 ms"]
Sleep --> StopTimer["Stop TaskTimer"]
StopTimer --> PrintElapsed["Print elapsed_ms"]
PrintElapsed --> ScheduleDemo["Schedule demo"]
ScheduleDemo --> CallNextRun["Call next_run() with cron & since"]
CallNextRun --> PrintNextRun["Print next run datetime"]

This flowchart depicts the sequential operations executed when running the demo script, highlighting the two main demonstrations: task timing and schedule calculation.


File Purpose Summary

The demo.py file functions as a concise example script that integrates the timing and scheduling modules, demonstrating their usage in practical scenarios. It provides users and developers a reference for how to apply the TaskTimer and next_run functionalities together, facilitating quick understanding and adoption of these components within the system.