Skip to content
Python project #23Advanced

Task Scheduler

Order dependent tasks topologically, detect cycles, compute the critical path with slack, and build a multi-worker schedule with a text Gantt chart.

Estimated time
~5 hours to build
Files
4 files · 313 lines
Technologies
Python 3, heapq, dataclasses

Introduction

Project planning tools answer three questions: in what order can tasks run, what is the shortest possible duration, and how long will it take with the people available? This scheduler answers all three with classic graph algorithms.

Problem statement

Read 'workers <n>' and lines 'task <id> <days> [after a,b] [: description]'. Reject malformed lines, duplicate tasks and unknown dependencies, and report circular dependencies with the cycle. Print a dependency order, each task's earliest start and finish and its slack, the shortest possible project duration and the critical path. Then schedule tasks on the given number of workers, always starting the ready task with the longest remaining chain, and draw a Gantt chart.

Objectives

  • Implement Kahn's topological sort
  • Detect and report cycles
  • Compute earliest/latest start times and slack (critical path method)
  • Write a list scheduler with heaps

Features

  • Dependency validation and cycle reporting
  • Stable topological order
  • Earliest start, finish and slack per task
  • Critical path
  • Multi-worker schedule and Gantt chart

Concepts demonstrated

  • Directed acyclic graphs
  • Topological sorting
  • Critical path method
  • Greedy list scheduling

System architecture

parse builds Task objects and links each to the tasks that depend on it. topological_order repeatedly removes tasks with no remaining prerequisites (alphabetical ties) and, if some remain, find_cycle follows dependencies until it repeats. critical_path runs a forward pass for earliest starts and a backward pass for latest starts and each task's tail (longest chain to the end). schedule simulates time: whenever a worker is idle it starts the ready task with the longest tail; otherwise it advances to the next finish event.

Folder structure

TextProject tree
task-scheduler/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

170 lines
Pythonmain.py
"""Task Scheduler: dependency ordering, critical path and a multi-worker schedule.
Input lines:
workers <n>
task <id> <days> [after <id>,<id>...] [: description]
Lines starting with '#' are comments.
"""
import heapq
import sys
from dataclasses import dataclass, field
class ScheduleError(Exception):
pass
@dataclass
class Task:
id: str
days: int
after: list[str]
description: str = ""
earliest_start: int = 0
latest_start: int = 0
tail: int = 0 # longest path from the start of this task to the end of the project
users: list[str] = field(default_factory=list)
@property
def slack(self) -> int:
return self.latest_start - self.earliest_start
def parse(text: str) -> tuple[dict[str, Task], int]:
tasks: dict[str, Task] = {}
workers = 1
for number, raw in enumerate(text.splitlines(), 1):
line = raw.split("#", 1)[0].strip()
if not line:
continue
head, _, description = line.partition(":")
words = head.split()
if words[0] == "workers" and len(words) == 2 and words[1].isdigit():
workers = int(words[1])
continue
if words[0] != "task" or len(words) not in (3, 5) or not words[2].isdigit() or (len(words) == 5 and words[3] != "after"):
raise ScheduleError(f"line {number}: expected 'task <id> <days> [after a,b]'")
if words[1] in tasks:
raise ScheduleError(f"line {number}: task {words[1]} defined twice")
after = words[4].split(",") if len(words) == 5 else []
tasks[words[1]] = Task(words[1], int(words[2]), after, description.strip())
for task in tasks.values():
for dep in task.after:
if dep not in tasks:
raise ScheduleError(f"task {task.id} depends on unknown task {dep}")
tasks[dep].users.append(task.id)
return tasks, workers
def topological_order(tasks: dict[str, Task]) -> list[str]:
"""Kahn's algorithm; ties broken alphabetically so the output is stable."""
remaining = {t.id: len(t.after) for t in tasks.values()}
ready = sorted(t for t, n in remaining.items() if n == 0)
order = []
while ready:
current = ready.pop(0)
order.append(current)
for user in tasks[current].users:
remaining[user] -= 1
if remaining[user] == 0:
ready.append(user)
ready.sort()
if len(order) != len(tasks):
raise ScheduleError("circular dependency: " + find_cycle(tasks, set(tasks) - set(order)))
return order
def find_cycle(tasks: dict[str, Task], candidates: set[str]) -> str:
start = min(candidates)
path, seen = [start], {start}
while True:
nxt = min(d for d in tasks[path[-1]].after if d in candidates)
if nxt in seen:
loop = path[path.index(nxt):] + [nxt]
return " -> ".join(reversed(loop))
path.append(nxt)
seen.add(nxt)
def critical_path(tasks: dict[str, Task], order: list[str]) -> tuple[int, list[str]]:
for tid in order: # forward pass
t = tasks[tid]
t.earliest_start = max((tasks[d].earliest_start + tasks[d].days for d in t.after), default=0)
duration = max(t.earliest_start + t.days for t in tasks.values())
for tid in reversed(order): # backward pass
t = tasks[tid]
t.latest_start = min((tasks[u].latest_start for u in t.users), default=duration) - t.days
t.tail = t.days + max((tasks[u].tail for u in t.users), default=0)
path, current = [], min((t for t in tasks.values() if not t.after and t.slack == 0), key=lambda t: t.id)
while True:
path.append(current.id)
nxt = [tasks[u] for u in current.users if tasks[u].slack == 0 and tasks[u].earliest_start == current.earliest_start + current.days]
if not nxt:
break
current = min(nxt, key=lambda t: t.id)
return duration, path
def schedule(tasks: dict[str, Task], workers: int) -> tuple[list[tuple[str, int, int, int]], int]:
"""List scheduling: whenever a worker is free, start the ready task with the longest tail."""
remaining = {t.id: len(t.after) for t in tasks.values()}
finish: dict[str, int] = {}
ready = [(-t.tail, t.id) for t in tasks.values() if not t.after]
heapq.heapify(ready)
free_at = [0] * workers
running: list[tuple[int, str]] = []
plan = []
clock = 0
while len(finish) < len(tasks):
# ready holds (-tail, id), so min() picks the task with the longest remaining path
startable = [(neg_tail, tid) for neg_tail, tid in ready if max((finish[d] for d in tasks[tid].after), default=0) <= clock]
idle = [w for w in range(workers) if free_at[w] <= clock]
if startable and idle:
_, tid = min(startable)
ready.remove(next(e for e in ready if e[1] == tid))
heapq.heapify(ready)
worker = idle[0]
end = clock + tasks[tid].days
free_at[worker] = end
heapq.heappush(running, (end, tid))
plan.append((tid, worker + 1, clock, end))
continue
end, tid = heapq.heappop(running)
clock = max(clock, end)
finish[tid] = end
for user in tasks[tid].users:
remaining[user] -= 1
if remaining[user] == 0:
heapq.heappush(ready, (-tasks[user].tail, user))
return plan, max(finish.values())
def main() -> None:
try:
tasks, workers = parse(sys.stdin.read())
if not tasks:
raise ScheduleError("no tasks given")
order = topological_order(tasks)
except ScheduleError as error:
print(f"Error: {error}")
return
duration, path = critical_path(tasks, order)
print("Dependency order: " + " ".join(order))
print(f"\n{'Task':<9}{'Days':>5}{'Start':>7}{'Finish':>8}{'Slack':>7} Description")
for tid in order:
t = tasks[tid]
mark = " *" if t.slack == 0 else ""
print(f"{t.id:<9}{t.days:>5}{t.earliest_start:>7}{t.earliest_start + t.days:>8}{t.slack:>7} {t.description}{mark}")
print(f"\nShortest possible duration (unlimited workers): {duration} days")
print("Critical path: " + " -> ".join(path) + " (* = no slack)")
plan, total = schedule(tasks, workers)
print(f"\nSchedule with {workers} worker{'s' if workers > 1 else ''}: {total} days")
for tid, worker, start, end in sorted(plan, key=lambda p: (p[2], p[1])):
bar = " " * start + "#" * (end - start)
print(f" W{worker} {tid:<9}{start:>3}-{end:<3}|{bar}")
if __name__ == "__main__":
main()

What each file does

main.py
Parsing, topological sorting with cycle detection, the critical-path passes, the worker schedule and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Dependency order: plan content db api design ui wire test launch
Task Days Start Finish Slack Description
plan 2 0 2 0 gather requirements *
content 2 2 4 9 write page text
db 4 2 6 0 database schema *
api 5 6 11 0 back-end API *
design 3 2 5 2 wireframes and colours
ui 4 5 9 2 front-end pages
wire 2 11 13 0 connect pages to the API *
test 3 13 16 0 testing *
launch 1 16 17 0 deploy *
Shortest possible duration (unlimited workers): 17 days
Critical path: plan -> db -> api -> wire -> test -> launch (* = no slack)
Schedule with 2 workers: 17 days
W1 plan 0-2 |##
W1 db 2-6 | ####
W2 design 2-5 | ###
W2 ui 5-9 | ####
W1 api 6-11 | #####
W2 content 9-11 | ##
W1 wire 11-13 | ##
W1 test 13-16 | ###
W1 launch 16-17 | #
Input
# A small website project
workers 2
task plan 2 : gather requirements
task design 3 after plan : wireframes and colours
task db 4 after plan : database schema
task api 5 after db : back-end API
task ui 4 after design : front-end pages
task content 2 after plan : write page text
task wire 2 after api,ui : connect pages to the API
task test 3 after wire,content : testing
task launch 1 after test : deploy

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • The critical path is plan -> db -> api -> wire -> test -> launch, giving 17 days.
  • content has 9 days of slack and design and ui have 2.
  • With two workers the schedule still finishes in 17 days because db (on the critical path) starts first.

Common errors

The scheduler starts short tasks first and the project takes longer

Prioritise ready tasks by their tail (longest remaining chain), not by duration or name.

Infinite loop on circular dependencies

Detect leftover tasks after the topological sort and report the cycle instead of scheduling.

Possible improvements

  • Read tasks from CSV
  • Assign tasks to named workers with skills
  • Add calendar dates and skip weekends

Additional challenges

  1. 1Show how the duration changes from 1 to 5 workers.
  2. 2Allow tasks to be split across days.
  3. 3Export the schedule as a Mermaid Gantt diagram.

Built and tested it yourself? Mark it to update your dashboard.