demo.py
Overview
This script serves as a practical demonstration of two primary functionalities within the system:
Task Timing: Utilizing the
TaskTimerclass from thePrecise Task Timingmodule to measure elapsed time for a short, simulated task with millisecond precision.Scheduled Task Execution: Leveraging the
next_runfunction from theNext Run Calculationmodule 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
TaskTimerfromtasktimer: Provides the timer utility to measure elapsed time with millisecond precision.next_runfromtasktimer.schedule: Calculates the next datetime matching a given cron-like schedule after a reference time.datetimefrom Python standard library: Used to specify reference datetimes for scheduling.
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")
What it does:
Creates an instance of
TaskTimerand immediately starts it.Simulates a task by sleeping for 50 milliseconds (
time.sleep(0.05)).Stops the timer.
Prints the elapsed time in milliseconds.
Parameters:
No explicit parameters for
TaskTimer()or.start().time.sleep(0.05)pauses execution for 0.05 seconds.
Return Values:
t.elapsed_msreturns the elapsed time in milliseconds as an integer or float.
Usage Notes:
This example demonstrates the typical usage pattern of the timer: start → execute task → stop → read elapsed time.
The timer is precise enough to measure short durations on the order of milliseconds.
Related Topics:
See
Timer Usage Demofor practical usage patterns.See
Precise Task Timingfor implementation details ofTaskTimer.
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)
What it does:
Calls
next_runto calculate the next occurrence of a cron schedule"0 9 * * *"which corresponds to 9:00 AM every day.Uses a reference datetime of October 2, 2025, 08:59 AM.
Prints the calculated next scheduled run datetime.
Parameters:
cron(str):"0 9 * * *"— a standard five-field cron expression specifying minute, hour, day of month, month, and day of week.since(datetime): Adatetimeobject from which to start the search for the next run time.
Return Values:
nr(datetime): The calculated datetime that matches the cron schedule and occurs after thesincedatetime.
Usage Notes:
This demonstrates how to use cron-like syntax for scheduling calculations.
The example uses a fixed date/time for reproducibility.
Related Topics:
See
Next Run Calculationfor the algorithm used.See
Scheduling Demonstrationfor practical usage of scheduling functions.See
Cron Schedule Parsingfor details on parsing cron expressions.
Interaction with Other Modules
TaskTimer (
tasktimer):The demo imports and uses
TaskTimerto measure elapsed time accurately.This class is implemented in
Precise Task Timing.The timer utility depends on system time but abstracts it via the
now_ts()function to ensure precision and testability.
Schedule Module (
tasktimer.schedule):The demo imports
next_runfrom the schedule module to compute next scheduled execution time.The schedule module encapsulates cron expression parsing and iteration logic to find the next matching datetime.
This logic is detailed in
Next Run CalculationandCron Schedule Parsing.
Standard Library:
Uses
datetimefor specifying reference times.Uses
time.sleepto simulate a delay in the timing demo.
Important Implementation Details
The demo script uses
time.sleep(0.05)to simulate a delay that theTaskTimerwill measure. This short delay is sufficient to demonstrate millisecond precision.The
next_runfunction is called with a hardcoded cron expression andsincedatetime to demonstrate calculation of scheduled times.Both the timer and scheduling functions are called sequentially and output their results via
print()statements.
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.