Add cron next-run display and speed up timer lookup

This commit is contained in:
mdaleo404 committed 2026-10-02 14:31:44 +01:00
1 parent 6e49e6c47e
commit 8942978923
11 files changed
+328 -14

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ daemon, not a queue, and not a replacement scheduler.
$ schedls $ schedls
NAME SCHEDULE NEXT BACKEND SCOPE STATUS NAME SCHEDULE NEXT BACKEND SCOPE STATUS
backup daily at 02:00 tomorrow 02:00 systemd user waiting backup daily at 02:00 tomorrow 02:00 systemd user waiting
cleanup 0 4 * * 0 — cron user active cleanup 0 4 * * 0 Sun 04:00 cron user active
logrotate daily — systemd system waiting logrotate daily — systemd system waiting
``` ```
+7 -3
View File
@@ -54,9 +54,13 @@ written to stderr as `Note:` lines.
$ schedls show backup $ schedls show backup
``` ```
Shows one job in detail: status, backend and scope, whether schedls manages it, Shows one job in a field-oriented view: status, backend and scope, whether
the schedule, the next and previous runs, the command, the source paths, and any schedls manages it, the schedule, next and previous runs, the command, source
systemd extras (persistent, jitter, accuracy, working directory, environment). paths, and any systemd extras (persistent, jitter, accuracy, working directory,
environment). Human-readable cron next runs are calculated in the host's local
timezone; cron previous runs and results remain unavailable because cron
exposes no per-job execution history. To preserve the JSON document contract,
cron `next_run` remains `null` in `--json` output.
### `new NAME` ### `new NAME`
+9
View File
@@ -35,6 +35,15 @@ Periodic directories only contribute executable, run-parts-style file names.
Every unrelated line is preserved exactly. `schedls` does not reformat, sort, Every unrelated line is preserved exactly. `schedls` does not reformat, sort,
normalize, or rewrite crontab content it did not create. normalize, or rewrite crontab content it did not create.
## Run times
For five-field expressions and calendar nicknames, schedls calculates the next
cron occurrence in the host's local timezone for human-readable output.
`@reboot` has no wall-clock next run. Cron does not expose per-entry execution
history, so previous run times and results are shown as unavailable rather than
guessed. To keep the stable JSON document contract, cron `next_run` remains
`null` in `--json` output.
## Managed blocks ## Managed blocks
Jobs created by `schedls` in the current user's crontab live in a delimited Jobs created by `schedls` in the current user's crontab live in a delimited
+1 -1
View File
@@ -113,6 +113,6 @@ in CI.
## Availability, privacy ## Availability, privacy
`0.2.0` requires `systemd-analyze` to create or validate calendar expressions `0.3.0` requires `systemd-analyze` to create or validate calendar expressions
and refuses the operation if it is unavailable. `schedls` makes no network and refuses the operation if it is unavailable. `schedls` makes no network
requests and collects no telemetry. requests and collects no telemetry.
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "schedls" name = "schedls"
version = "0.2.0" version = "0.3.0"
description = "Inspect and manage Linux scheduled jobs" description = "Inspect and manage Linux scheduled jobs"
authors = [ authors = [
{ name = "Marco D'Aleo", email = "marco@marcodaleo.com" } { name = "Marco D'Aleo", email = "marco@marcodaleo.com" }
-1
View File
@@ -382,7 +382,6 @@ class CronBackend(SchedulerBackend):
schedule=Schedule(ScheduleKind.CRON, (job_line.expression or "") if job_line else ""), schedule=Schedule(ScheduleKind.CRON, (job_line.expression or "") if job_line else ""),
command=Command(argv=(), raw=job_line.command if job_line else ""), command=Command(argv=(), raw=job_line.command if job_line else ""),
source=JobSource("current user's crontab", line=block.begin_index), source=JobSource("current user's crontab", line=block.begin_index),
next_run=None,
last_run=None, last_run=None,
cron=CronDetails( cron=CronDetails(
expression=job_line.expression if job_line else None, expression=job_line.expression if job_line else None,
+30 -3
View File
@@ -77,6 +77,9 @@ class SystemdBackend(SchedulerBackend):
def __init__(self, runner: CommandRunner) -> None: def __init__(self, runner: CommandRunner) -> None:
self.runner = runner self.runner = runner
self._manager_ok: dict[Scope, bool] = {}
self._user_lingering_checked = False
self._user_lingering: bool | None = None
# -- capability detection ------------------------------------------------- # -- capability detection -------------------------------------------------
@@ -87,7 +90,10 @@ class SystemdBackend(SchedulerBackend):
return self.runner.has("systemd-analyze") return self.runner.has("systemd-analyze")
def manager_ok(self, scope: Scope) -> bool: def manager_ok(self, scope: Scope) -> bool:
if scope in self._manager_ok:
return self._manager_ok[scope]
if not self.has_systemctl(): if not self.has_systemctl():
self._manager_ok[scope] = False
return False return False
try: try:
completed = self.runner.run( completed = self.runner.run(
@@ -96,14 +102,19 @@ class SystemdBackend(SchedulerBackend):
check=False, check=False,
) )
except OperationalError: except OperationalError:
self._manager_ok[scope] = False
return False return False
state = completed.stdout.strip() state = completed.stdout.strip()
return state not in {"", "offline", "unknown"} self._manager_ok[scope] = state not in {"", "offline", "unknown"}
return self._manager_ok[scope]
def available(self) -> bool: def available(self) -> bool:
return self.has_systemctl() and (self.manager_ok(Scope.USER) or self.manager_ok(Scope.SYSTEM)) return self.has_systemctl() and (self.manager_ok(Scope.USER) or self.manager_ok(Scope.SYSTEM))
def user_lingering(self) -> bool | None: def user_lingering(self) -> bool | None:
if self._user_lingering_checked:
return self._user_lingering
self._user_lingering_checked = True
if not self.runner.has("loginctl"): if not self.runner.has("loginctl"):
return None return None
try: try:
@@ -116,7 +127,8 @@ class SystemdBackend(SchedulerBackend):
return None return None
if completed.returncode != 0: if completed.returncode != 0:
return None return None
return completed.stdout.strip().endswith("yes") self._user_lingering = completed.stdout.strip().endswith("yes")
return self._user_lingering
# -- calendar validation -------------------------------------------------- # -- calendar validation --------------------------------------------------
@@ -171,6 +183,20 @@ class SystemdBackend(SchedulerBackend):
jobs.append(job) jobs.append(job)
return jobs return jobs
def find(self, name: str) -> ScheduledJob | None:
"""Look up a timer directly instead of discovering every timer."""
candidates = (f"schedls-{name}.timer", f"{name}.timer")
for scope in (Scope.USER, Scope.SYSTEM):
if not self.manager_ok(scope):
continue
for unit in candidates:
if not is_safe_unit_name(unit):
continue
job = self._build_job(unit, scope)
if job is not None and job.name == name:
return job
return None
def _list_timer_units(self, scope: Scope) -> list[str]: def _list_timer_units(self, scope: Scope) -> list[str]:
units: list[str] = [] units: list[str] = []
seen: set[str] = set() seen: set[str] = set()
@@ -212,6 +238,7 @@ class SystemdBackend(SchedulerBackend):
service_unit = None service_unit = None
service_fragment = None service_fragment = None
service_sections = None service_sections = None
service_props: dict[str, str] = {}
if service_unit: if service_unit:
service_props = self._show(service_unit, scope) service_props = self._show(service_unit, scope)
service_fragment = service_props.get("FragmentPath") or None service_fragment = service_props.get("FragmentPath") or None
@@ -227,7 +254,7 @@ class SystemdBackend(SchedulerBackend):
command = _command_from_service(service_sections) command = _command_from_service(service_sections)
next_run = parse_systemd_timestamp(properties.get("NextElapseUSecRealtime", "")) next_run = parse_systemd_timestamp(properties.get("NextElapseUSecRealtime", ""))
last_run = parse_systemd_timestamp(properties.get("LastTriggerUSec", "")) last_run = parse_systemd_timestamp(properties.get("LastTriggerUSec", ""))
last_result = properties.get("Result") or None last_result = service_props.get("Result") or properties.get("Result") or None
details = SystemdDetails( details = SystemdDetails(
timer_unit=unit, timer_unit=unit,
+140
View File
@@ -0,0 +1,140 @@
"""Calculate upcoming occurrences for the cron syntax schedls accepts."""
from __future__ import annotations
from datetime import UTC, date, datetime, time, timedelta, tzinfo
from zoneinfo import ZoneInfo
_NICKNAMES = {
"@yearly": "0 0 1 1 *",
"@annually": "0 0 1 1 *",
"@monthly": "0 0 1 * *",
"@weekly": "0 0 * * 0",
"@daily": "0 0 * * *",
"@midnight": "0 0 * * *",
"@hourly": "0 * * * *",
}
_MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
_WEEKDAYS = {"sun": 0, "mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat": 6}
def next_occurrence(expression: str, *, after: datetime | None = None) -> datetime | None:
"""Return the next local occurrence, or ``None`` when it cannot be known.
``@reboot`` and unsupported foreign expressions have no calculable
wall-clock next occurrence.
"""
expression = expression.lower()
if expression == "@reboot":
return None
expression = _NICKNAMES.get(expression, expression)
try:
minute_text, hour_text, dom_text, month_text, dow_text = expression.split()
minutes, _ = _field_values(minute_text, 0, 59)
hours, _ = _field_values(hour_text, 0, 23)
days, dom_any = _field_values(dom_text, 1, 31)
months, _ = _field_values(month_text, 1, 12, aliases=_MONTHS)
weekdays, dow_any = _field_values(dow_text, 0, 7, aliases=_WEEKDAYS)
except ValueError:
return None
weekdays = {value % 7 for value in weekdays}
reference = after or datetime.now(_local_timezone())
if reference.tzinfo is None:
raise ValueError("after must include a timezone")
zone = reference.tzinfo
reference = reference.astimezone(zone)
times = [(hour, minute) for hour in sorted(hours) for minute in sorted(minutes)]
# Gregorian leap days can be eight years apart across a non-leap century.
for offset in range(9 * 366):
candidate_date = reference.date() + timedelta(days=offset)
if not _date_matches(candidate_date, months, days, weekdays, dom_any=dom_any, dow_any=dow_any):
continue
for hour, minute in times:
candidate = datetime.combine(candidate_date, time(hour, minute), tzinfo=zone)
if not _is_real_local_time(candidate, zone) or candidate <= reference:
continue
return candidate
return None
def _field_values(
field: str,
low: int,
high: int,
*,
aliases: dict[str, int] | None = None,
) -> tuple[set[int], bool]:
values: set[int] = set()
unrestricted = field == "*"
for part in field.split(","):
base, separator, step_text = part.partition("/")
step = int(step_text) if separator else 1
if step < 1:
raise ValueError("invalid step")
if base == "*":
start, end = low, high
elif "-" in base:
start_text, end_text = base.split("-", 1)
start = _field_value(start_text, aliases)
end = _field_value(end_text, aliases)
else:
start = end = _field_value(base, aliases)
if not (low <= start <= high and low <= end <= high and start <= end):
raise ValueError("field out of range")
values.update(range(start, end + 1, step))
return values, unrestricted
def _field_value(value: str, aliases: dict[str, int] | None) -> int:
if aliases and value in aliases:
return aliases[value]
return int(value)
def _date_matches(
candidate: date,
months: set[int],
days: set[int],
weekdays: set[int],
*,
dom_any: bool,
dow_any: bool,
) -> bool:
if candidate.month not in months:
return False
dom_matches = candidate.day in days
cron_weekday = (candidate.weekday() + 1) % 7
dow_matches = cron_weekday in weekdays
if dom_any:
return dow_matches
if dow_any:
return dom_matches
return dom_matches or dow_matches
def _is_real_local_time(candidate: datetime, zone: tzinfo) -> bool:
normalized = candidate.astimezone(UTC).astimezone(zone)
return normalized.replace(tzinfo=None) == candidate.replace(tzinfo=None)
def _local_timezone() -> tzinfo:
try:
with open("/etc/localtime", "rb") as handle:
return ZoneInfo.from_file(handle)
except (OSError, ValueError):
return datetime.now().astimezone().tzinfo or UTC
+28 -4
View File
@@ -4,8 +4,10 @@ from __future__ import annotations
import os import os
from collections.abc import Sequence from collections.abc import Sequence
from datetime import datetime
from ..backends.base import SchedulerBackend from ..backends.base import SchedulerBackend
from ..cronexpr import next_occurrence
from ..errors import SchedlsError from ..errors import SchedlsError
from ..models import Backend, ScheduledJob, Scope from ..models import Backend, ScheduledJob, Scope
from ..output import Output, jobs_document from ..output import Output, jobs_document
@@ -76,7 +78,8 @@ def render_list(output: Output, jobs: Sequence[ScheduledJob], warnings: Sequence
else: else:
rows = [] rows = []
for job in jobs: for job in jobs:
next_text = format_short(job.next_run, utc=output.utc) if job.next_run else "—" next_run = _next_run(job)
next_text = format_short(next_run, utc=output.utc) if next_run else "—"
rows.append( rows.append(
[ [
job.name, job.name,
@@ -89,7 +92,7 @@ def render_list(output: Output, jobs: Sequence[ScheduledJob], warnings: Sequence
) )
output.table(["NAME", "SCHEDULE", "NEXT", "BACKEND", "SCOPE", "STATUS"], rows) output.table(["NAME", "SCHEDULE", "NEXT", "BACKEND", "SCOPE", "STATUS"], rows)
for warning in warnings: for warning in warnings:
output.diagnostic(f"Note: {warning}") output.diagnostic(f"\nNote: {warning}")
def render_show(output: Output, job: ScheduledJob) -> None: def render_show(output: Output, job: ScheduledJob) -> None:
@@ -109,9 +112,10 @@ def render_show(output: Output, job: ScheduledJob) -> None:
for expression in job.schedule.expressions: for expression in job.schedule.expressions:
output.key_values([("OnCalendar", expression)]) output.key_values([("OnCalendar", expression)])
output.line() output.line()
output.key_values([("Next", output.job_datetime(job.next_run) or "unknown")]) next_run = _next_run(job)
output.key_values([("Next", output.job_datetime(next_run) or _next_unavailable(job))])
output.line() output.line()
previous = output.job_datetime(job.last_run) or "unknown" previous = output.job_datetime(job.last_run) or _previous_unavailable(job)
if job.last_result: if job.last_result:
previous = f"{previous}\nresult: {job.last_result}" previous = f"{previous}\nresult: {job.last_result}"
output.key_values([("Previous", previous)]) output.key_values([("Previous", previous)])
@@ -156,3 +160,23 @@ def _backend_label(job: ScheduledJob) -> str:
if job.backend is Backend.SYSTEMD: if job.backend is Backend.SYSTEMD:
return f"systemd {job.scope.value} timer" return f"systemd {job.scope.value} timer"
return "cron" return "cron"
def _next_unavailable(job: ScheduledJob) -> str:
if job.backend is Backend.CRON and job.schedule.expression.lower() == "@reboot":
return "unavailable (@reboot has no wall-clock next run)"
return "unavailable"
def _next_run(job: ScheduledJob) -> datetime | None:
if job.next_run is not None:
return job.next_run
if job.backend is Backend.CRON:
return next_occurrence(job.schedule.expression)
return None
def _previous_unavailable(job: ScheduledJob) -> str:
if job.backend is Backend.CRON:
return "unavailable (cron does not provide per-job history)"
return "unavailable"
+45
View File
@@ -0,0 +1,45 @@
from __future__ import annotations
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
from schedls.cronexpr import next_occurrence
def test_next_occurrence_for_hourly_schedule() -> None:
after = datetime(2026, 10, 2, 12, 17, 30, tzinfo=UTC)
assert next_occurrence("17 * * * *", after=after) == datetime(2026, 10, 2, 13, 17, tzinfo=UTC)
def test_next_occurrence_uses_cron_day_of_month_or_weekday() -> None:
after = datetime(2026, 10, 12, 12, 0, tzinfo=UTC)
assert next_occurrence("0 0 13 * fri", after=after) == datetime(2026, 10, 13, 0, 0, tzinfo=UTC)
def test_next_occurrence_treats_day_steps_as_restricted() -> None:
after = datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
assert next_occurrence("0 0 */2 * *", after=after) == datetime(2026, 10, 3, 0, 0, tzinfo=UTC)
assert next_occurrence("0 0 * * */2", after=after) == datetime(2026, 10, 3, 0, 0, tzinfo=UTC)
def test_next_occurrence_supports_nicknames_and_reboot() -> None:
after = datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
assert next_occurrence("@daily", after=after) == datetime(2026, 10, 3, 0, 0, tzinfo=UTC)
assert next_occurrence("@reboot", after=after) is None
def test_next_occurrence_skips_nonexistent_local_time() -> None:
london = ZoneInfo("Europe/London")
after = datetime(2026, 3, 29, 0, 0, tzinfo=london)
assert next_occurrence("30 1 * * *", after=after) == datetime(2026, 3, 30, 1, 30, tzinfo=london)
def test_next_occurrence_handles_long_leap_day_gap() -> None:
after = datetime(2096, 3, 1, 0, 0, tzinfo=UTC)
assert next_occurrence("0 0 29 2 *", after=after) == datetime(2104, 2, 29, 0, 0, tzinfo=UTC)
+66
View File
@@ -15,6 +15,7 @@ from schedls.interact import Interaction
from schedls.models import ( from schedls.models import (
Backend, Backend,
Command, Command,
CronDetails,
JobSource, JobSource,
JobSpec, JobSpec,
Schedule, Schedule,
@@ -72,6 +73,45 @@ def test_render_show() -> None:
assert "systemd user timer" in text assert "systemd user timer" in text
def test_render_show_explains_unavailable_cron_history() -> None:
job = ScheduledJob(
name="cron-1",
backend=Backend.CRON,
scope=Scope.USER,
managed=False,
enabled=None,
schedule=Schedule(ScheduleKind.CRON, "0 2 * * *"),
command=Command(raw="/usr/bin/backup"),
source=JobSource("current user's crontab", line=1),
cron=CronDetails(expression="0 2 * * *", line=1),
)
output, stream = _output()
inspect_ops.render_show(output, job)
assert "Previous unavailable (cron does not provide per-job history)" in stream.getvalue()
def test_render_show_keeps_cron_next_run_null_in_json() -> None:
job = ScheduledJob(
name="cron-1",
backend=Backend.CRON,
scope=Scope.USER,
managed=False,
enabled=None,
schedule=Schedule(ScheduleKind.CRON, "0 2 * * *"),
command=Command(raw="/usr/bin/backup"),
source=JobSource("current user's crontab", line=1),
cron=CronDetails(expression="0 2 * * *", line=1),
)
output, stream = _output()
output.json_mode = True
inspect_ops.render_show(output, job)
assert '"next_run": null' in stream.getvalue()
def test_filter_jobs() -> None: def test_filter_jobs() -> None:
jobs = [_job(), _job("other")] jobs = [_job(), _job("other")]
assert inspect_ops.filter_jobs(jobs, managed=True) == jobs assert inspect_ops.filter_jobs(jobs, managed=True) == jobs
@@ -216,6 +256,32 @@ def test_systemd_backend_discovery_parses_units() -> None:
assert job.command.argv == ("/usr/local/bin/backup", "/srv/data") assert job.command.argv == ("/usr/local/bin/backup", "/srv/data")
assert job.enabled is True assert job.enabled is True
assert job.next_run is not None assert job.next_run is not None
assert job.last_result == "success"
def test_systemd_find_uses_direct_lookup_and_cached_manager_check() -> None:
def systemctl(argv, _input):
if "is-system-running" in argv:
return ("running\n", "")
if "show" in argv:
unit = argv[argv.index("show") + 1]
if unit == "schedls-backup.timer":
return ("LoadState=not-found\n", "")
if unit == "backup.timer":
return ("LoadState=loaded\nUnitFileState=enabled\n", "")
return ("", "")
runner = FakeRunner(handlers={"systemctl": systemctl}, available={"systemctl"})
backend = SystemdBackend(runner)
assert backend.available() is True
job = backend.find("backup")
assert job is not None
assert job.name == "backup"
calls = [argv for argv, _, _ in runner.calls]
assert sum("is-system-running" in argv for argv in calls) == 1
assert not any("list-unit-files" in argv or "list-units" in argv for argv in calls)
def test_plan_update_refuses_unmanaged() -> None: def test_plan_update_refuses_unmanaged() -> None: