-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.py
More file actions
executable file
·733 lines (626 loc) · 23.4 KB
/
Copy pathtimer.py
File metadata and controls
executable file
·733 lines (626 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
#!/usr/bin/env python3
import sys
import time
import re
import argparse
import os
import subprocess
import tempfile
import json
import signal
from pathlib import Path
__version__ = "1.0.7"
DEFAULT_GROUP = "default"
def parse_time(time_str):
"""
Parses a natural language time string into total seconds.
Supports years, days, hours, minutes, seconds.
Default unit is minutes if no unit is specified for a number.
Raises ValueError if unrecognized content is found.
"""
time_str = time_str.lower()
pattern = r'(\d+(?:\.\d+)?)\s*([a-z]*)'
matches = list(re.finditer(pattern, time_str))
total_seconds = 0
last_pos = 0
units = {
'y': 31536000, 'year': 31536000, 'years': 31536000,
'w': 604800, 'week': 604800, 'weeks': 604800,
'd': 86400, 'day': 86400, 'days': 86400,
'h': 3600, 'hour': 3600, 'hours': 3600,
'm': 60, 'min': 60, 'minute': 60, 'minutes': 60,
's': 1, 'sec': 1, 'second': 1, 'seconds': 1
}
for match in matches:
unrecognized = time_str[last_pos:match.start()].strip()
if unrecognized:
raise ValueError(f"Unrecognized input: '{unrecognized}'")
amount_str = match.group(1)
unit_str = match.group(2)
amount = float(amount_str)
unit = unit_str.strip()
if not unit:
multiplier = 60
elif unit in units:
multiplier = units[unit]
else:
raise ValueError(f"Unrecognized unit: '{unit}'")
total_seconds += amount * multiplier
last_pos = match.end()
unrecognized = time_str[last_pos:].strip()
if unrecognized:
raise ValueError(f"Unrecognized input: '{unrecognized}'")
return total_seconds
def format_duration_short(seconds):
if seconds <= 0:
return "0s"
YEAR = 31536000
WEEK = 604800
DAY = 86400
HOUR = 3600
MINUTE = 60
parts = []
years = int(seconds // YEAR)
seconds %= YEAR
weeks = int(seconds // WEEK)
seconds %= WEEK
days = int(seconds // DAY)
seconds %= DAY
hours = int(seconds // HOUR)
seconds %= HOUR
minutes = int(seconds // MINUTE)
seconds %= MINUTE
secs = int(seconds)
if years > 0:
parts.append(f"{years}y")
if weeks > 0:
parts.append(f"{weeks}w")
if days > 0:
parts.append(f"{days}d")
if hours > 0:
parts.append(f"{hours}h")
if minutes > 0:
parts.append(f"{minutes}m")
if secs > 0 or not parts:
parts.append(f"{secs}s")
return " ".join(parts)
TIMERS_DIR = Path(tempfile.gettempdir()) / "smart_timers"
def atomic_write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
tmp.replace(path)
def save_timer_info(name, pid, end_time, group=None, duration_seconds=None, paused=False, paused_remaining=None):
TIMERS_DIR.mkdir(exist_ok=True)
timer_file = TIMERS_DIR / f"timer_{pid}.json"
if group is None:
group = DEFAULT_GROUP
old = {}
if timer_file.exists():
try:
with open(timer_file, "r", encoding="utf-8") as f:
old = json.load(f)
except Exception:
old = {}
data = {
"name": name,
"pid": pid,
"end_time": end_time,
"group": group,
"paused": bool(paused),
}
if paused:
data["paused_remaining"] = float(paused_remaining if paused_remaining is not None else 0)
if duration_seconds is not None:
data["duration_seconds"] = duration_seconds
elif "duration_seconds" in old:
data["duration_seconds"] = old["duration_seconds"]
atomic_write_json(timer_file, data)
def write_timer_state(data):
"""Write full timer record (used by management commands)."""
pid = int(data["pid"])
timer_file = TIMERS_DIR / f"timer_{pid}.json"
atomic_write_json(timer_file, data)
def remove_timer_info(pid):
timer_file = TIMERS_DIR / f"timer_{pid}.json"
if timer_file.exists():
timer_file.unlink()
def read_timer_json(path):
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def iter_timer_paths():
if not TIMERS_DIR.exists():
return
for p in sorted(TIMERS_DIR.glob("timer_*.json")):
yield p
def normalize_timer_record(data):
data = dict(data)
data.setdefault("group", DEFAULT_GROUP)
data.setdefault("name", "")
data.setdefault("paused", False)
try:
data["pid"] = int(data["pid"])
data["end_time"] = float(data["end_time"])
except (KeyError, TypeError, ValueError):
return None
if data.get("paused"):
try:
data["paused_remaining"] = float(data["paused_remaining"])
except (KeyError, TypeError, ValueError):
data["paused_remaining"] = 0.0
if "duration_seconds" in data:
try:
data["duration_seconds"] = float(data["duration_seconds"])
except (TypeError, ValueError):
data.pop("duration_seconds", None)
return data
def effective_remaining(data, now=None):
if now is None:
now = time.time()
if data.get("paused"):
return max(0.0, float(data.get("paused_remaining", 0)))
return max(0.0, float(data["end_time"]) - now)
def list_timers(group_filter=None):
if not TIMERS_DIR.exists():
print("No running timers")
return
timer_files = list(TIMERS_DIR.glob("timer_*.json"))
if not timer_files:
print("No running timers")
return
rows = []
for timer_file in sorted(timer_files):
try:
data = normalize_timer_record(read_timer_json(timer_file))
if data is None:
continue
if group_filter is not None and data["group"] != group_filter:
continue
remaining = effective_remaining(data)
if not data.get("paused") and remaining <= 0:
timer_file.unlink()
continue
rows.append((data, remaining, timer_file))
except Exception:
continue
if not rows:
print("No running timers" + (f" in group '{group_filter}'" if group_filter else ""))
return
print("Running timers:" + (f" (group: {group_filter})" if group_filter else ""))
for data, remaining, _ in rows:
time_str = format_duration_short(remaining)
name = data.get("name") or "Timer"
grp = data.get("group", DEFAULT_GROUP)
state = "paused" if data.get("paused") else "running"
print(f" [{grp}] {name} {time_str} ({state}) pid={data['pid']}")
def sleep_system():
try:
subprocess.run(['pmset', 'sleepnow'], check=True)
except Exception as e:
print(f"Failed to sleep system: {e}")
def sleep_display():
try:
subprocess.run(['pmset', 'displaysleepnow'], check=True)
except Exception as e:
print(f"Failed to sleep display: {e}")
def _kill_pid(pid, grace=0.3):
if pid == os.getpid():
return
try:
if hasattr(signal, "SIGTERM"):
os.kill(pid, signal.SIGTERM)
else:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
return
except PermissionError:
pass
except OSError:
pass
t0 = time.time()
while time.time() - t0 < grace:
try:
os.kill(pid, 0)
except ProcessLookupError:
return
except OSError:
return
time.sleep(0.05)
try:
if hasattr(signal, "SIGKILL"):
os.kill(pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError, OSError):
pass
def stop_timers(predicate):
stopped = 0
for path in list(iter_timer_paths()):
try:
data = normalize_timer_record(read_timer_json(path))
if data is None or not predicate(data):
continue
_kill_pid(data["pid"])
path.unlink(missing_ok=True)
stopped += 1
except Exception:
continue
return stopped
def set_pause_state(predicate, pause):
changed = 0
now = time.time()
for path in list(iter_timer_paths()):
try:
data = normalize_timer_record(read_timer_json(path))
if data is None or not predicate(data):
continue
if pause:
if data.get("paused"):
continue
rem = max(0.0, float(data["end_time"]) - now)
data["paused"] = True
data["paused_remaining"] = rem
write_timer_state(data)
changed += 1
else:
if not data.get("paused"):
continue
rem = max(0.0, float(data.get("paused_remaining", 0)))
data["paused"] = False
data["end_time"] = now + rem
if "paused_remaining" in data:
del data["paused_remaining"]
write_timer_state(data)
changed += 1
except Exception:
continue
return changed
def reset_timers(predicate):
changed = 0
now = time.time()
for path in list(iter_timer_paths()):
try:
data = normalize_timer_record(read_timer_json(path))
if data is None or not predicate(data):
continue
dur = data.get("duration_seconds")
if dur is None or dur <= 0:
continue
data["paused"] = False
data.pop("paused_remaining", None)
data["end_time"] = now + float(dur)
write_timer_state(data)
changed += 1
except Exception:
continue
return changed
def parse_adjust_delta(s):
s = s.strip()
if not s:
raise ValueError("empty adjust string")
sign = 1.0
if s[0] in "+-":
if s[0] == "-":
sign = -1.0
s = s[1:].strip()
sec = parse_time(s)
return sign * sec
def adjust_timers_by_name(name, delta_seconds, group_filter=None):
if not name:
return 0
now = time.time()
changed = 0
for path in list(iter_timer_paths()):
try:
data = normalize_timer_record(read_timer_json(path))
if data is None:
continue
if group_filter is not None and data.get("group") != group_filter:
continue
if (data.get("name") or "") != name:
continue
if data.get("paused"):
base = float(data.get("paused_remaining", 0))
else:
base = max(0.0, float(data["end_time"]) - now)
new_rem = max(0.0, base + delta_seconds)
if new_rem <= 0:
new_rem = 0.0
if data.get("paused"):
data["paused_remaining"] = new_rem
else:
data["end_time"] = now + new_rem
write_timer_state(data)
changed += 1
except Exception:
continue
return changed
class CustomArgumentParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write(f"Error: {message}\n")
sys.stderr.write("Try 'timer --help' for more information.\n")
sys.exit(2)
TIMER_HELP_EPILOG = f"""
Unique to this CLI:
• Live control without restarting the countdown process: pause, resume, add/subtract
time (--adjust) while the same timer keeps running in another shell — state is synced
via JSON in the OS temp directory under smart_timers/ (see tempfile.gettempdir();
often $TMPDIR on Unix)
• Named groups (-g): default group is "{DEFAULT_GROUP}" (like a primary group); filter
-ls, or stop/pause/reset a whole team of background timers at once.
Quick examples:
timer 25m -n Pomodoro -g work &
timer -ls -g work
timer --pause -n Pomodoro
timer --adjust +10m -n Pomodoro
timer --resume -n Pomodoro
timer --reset-group work
timer --stop-all
Notes:
--reset-* needs duration_seconds in state (timers started with this version).
--stop / --pause / --resume / --reset (single timer) need -n; add -g if names collide.
--clear-all and --clear-group are aliases for --stop-all / --stop-group.
""".strip()
def poll_timer_state(pid):
path = TIMERS_DIR / f"timer_{pid}.json"
if not path.exists():
return None
try:
return normalize_timer_record(read_timer_json(path))
except Exception:
return None
def run_countdown_loop(args, pid, duration_seconds, initial_end_time):
end_time = initial_end_time
group = args.group or DEFAULT_GROUP
def persist(end_t, dur=None, paused=False, paused_rem=None):
save_timer_info(
args.name,
pid,
end_t,
group=group,
duration_seconds=dur if dur is not None else duration_seconds,
paused=paused,
paused_remaining=paused_rem,
)
persist(end_time, duration_seconds, paused=False)
try:
while True:
start_time = time.time()
end_time = start_time + duration_seconds
persist(end_time, duration_seconds, paused=False)
while True:
state = poll_timer_state(pid)
if state is None:
remove_timer_info(pid)
return
if state.get("paused"):
rem = float(state.get("paused_remaining", 0))
time_str = format_duration_short(rem)
else:
end_time = float(state["end_time"])
now = time.time()
remaining = end_time - now
if remaining <= 0:
break
time_str = format_duration_short(remaining)
if args.name:
output = f"\r\033[K{args.name} {time_str}"
else:
output = f"\r\033[K{time_str}"
sys.stdout.write(output)
sys.stdout.flush()
time.sleep(0.12)
if args.name:
print(f"\r\033[K{args.name} Done!")
else:
print(f"\r\033[KDone!")
sys.stdout.write('\a')
sys.stdout.flush()
if args.synchronize:
continue
remove_timer_info(pid)
if args.sleep:
sleep_system()
elif args.sleep_display:
sleep_display()
if args.execute:
try:
subprocess.run(args.execute, shell=True)
except Exception as e:
print(f"\nError executing command: {e}")
break
except KeyboardInterrupt:
remove_timer_info(pid)
if args.name:
print(f"\n\033[K{args.name} Cancelled")
else:
print(f"\n\033[KCancelled")
sys.exit(0)
def main():
parser = CustomArgumentParser(
description=(
"Minimal Timer — smart countdown with natural time parsing, optional labels, "
"and orchestration of many background timers via groups (no separate daemon)."
),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=TIMER_HELP_EPILOG,
)
parser.add_argument(
'time_input',
nargs='*',
help="Duration to count down, e.g. 10m, 1h 30s, 2d (bare number = minutes).",
)
parser.add_argument('-n', '--name', type=str, default="", help="Label for this timer (required for --stop/--pause/--resume/--reset/--adjust on one timer).")
parser.add_argument(
'-g', '--group',
type=str,
default=None,
help=f"Logical group for this timer (default when omitted: '{DEFAULT_GROUP}'). Use with -ls or batch flags to target a subset.",
)
parser.add_argument('-s', '--sleep', action='store_true', help="macOS: put the system to sleep when the countdown finishes.")
parser.add_argument('-sd', '--sleep-display', action='store_true', help="macOS: turn display off when the countdown finishes.")
parser.add_argument('-e', '--execute', type=str, help="Shell command to run after the countdown finishes (once, unless -sync).")
parser.add_argument('-sync', '--synchronize', action='store_true', help="Loop: beep and restart the same duration until Ctrl+C.")
parser.add_argument('-ls', '--list', action='store_true', help="List running timers; add -g GROUP to show only that group (shows group, remaining, paused/running, pid).")
parser.add_argument('-v', '--version', action='store_true', help="Print version and exit.")
parser.add_argument('--stop-all', action='store_true', help="Kill every tracked timer process and delete all state files.")
parser.add_argument('--stop-group', metavar='GROUP', help="Kill all timers whose group is GROUP.")
parser.add_argument('--stop', action='store_true', help="Kill timer(s) with exact name from -n; optional -g disambiguates duplicates.")
parser.add_argument('--pause-all', action='store_true', help="Pause every running timer (freeze remaining; no new process).")
parser.add_argument('--pause-group', metavar='GROUP', help="Pause all timers in GROUP.")
parser.add_argument('--pause', action='store_true', help="Pause by -n (and optional -g); or use --pause-all / --pause-group.")
parser.add_argument('--resume-all', action='store_true', help="Resume every timer that was paused with the pause-* commands.")
parser.add_argument('--resume-group', metavar='GROUP', help="Resume all paused timers in GROUP.")
parser.add_argument('--resume', action='store_true', help="Resume by -n (and optional -g).")
parser.add_argument(
'--reset-all',
action='store_true',
help="Set each timer's end time to now + saved original duration (skipped if duration_seconds missing in state).",
)
parser.add_argument('--reset-group', metavar='GROUP', help="Same as --reset-all but only for timers in GROUP.")
parser.add_argument('--reset', action='store_true', help="Reset one named timer (-n, optional -g) to its original duration.")
parser.add_argument('--clear-all', action='store_true', help="Same as --stop-all (naming alias).")
parser.add_argument('--clear-group', metavar='GROUP', help="Same as --stop-group.")
parser.add_argument(
'--adjust',
metavar='DELTA',
type=str,
help="Change remaining time on running/paused timer(s) named with -n: same syntax as duration, with leading + or -, e.g. +10d, -5m. Optional -g.",
)
args = parser.parse_args()
if args.version:
print(f"Minimal Timer v{__version__}")
return
mgmt = any([
args.list, args.stop_all, args.stop_group, args.stop,
args.pause_all, args.pause_group, args.pause,
args.resume_all, args.resume_group, args.resume,
args.reset_all, args.reset_group, args.reset,
args.clear_all, args.clear_group, args.adjust is not None,
])
if args.clear_all:
args.stop_all = True
if args.clear_group:
args.stop_group = args.clear_group
if args.list:
list_timers(group_filter=args.group)
sys.exit(0)
group_f = args.group
def pred_all(_d):
return True
if args.stop_all:
n = stop_timers(pred_all)
print(f"Stopped {n} timer(s).")
sys.exit(0)
if args.stop_group:
g = args.stop_group
n = stop_timers(lambda d: d.get("group", DEFAULT_GROUP) == g)
print(f"Stopped {n} timer(s) in group '{g}'.")
sys.exit(0)
if args.stop:
name = args.name or ""
if not name:
print("Error: --stop requires -n/--name")
sys.exit(2)
n = stop_timers(
lambda d: (d.get("name") or "") == name
and (group_f is None or d.get("group", DEFAULT_GROUP) == group_f)
)
print(f"Stopped {n} timer(s) named '{name}'.")
sys.exit(0)
if args.pause_all:
n = set_pause_state(pred_all, True)
print(f"Paused {n} timer(s).")
sys.exit(0)
if args.pause_group:
g = args.pause_group
n = set_pause_state(lambda d: d.get("group", DEFAULT_GROUP) == g, True)
print(f"Paused {n} timer(s) in group '{g}'.")
sys.exit(0)
if args.pause:
name = args.name or ""
if not name:
print("Error: --pause requires -n/--name (or use --pause-all / --pause-group)")
sys.exit(2)
n = set_pause_state(
lambda d: (d.get("name") or "") == name
and (group_f is None or d.get("group", DEFAULT_GROUP) == group_f),
True,
)
print(f"Paused {n} timer(s) named '{name}'.")
sys.exit(0)
if args.resume_all:
n = set_pause_state(pred_all, False)
print(f"Resumed {n} timer(s).")
sys.exit(0)
if args.resume_group:
g = args.resume_group
n = set_pause_state(lambda d: d.get("group", DEFAULT_GROUP) == g, False)
print(f"Resumed {n} timer(s) in group '{g}'.")
sys.exit(0)
if args.resume:
name = args.name or ""
if not name:
print("Error: --resume requires -n/--name (or use --resume-all / --resume-group)")
sys.exit(2)
n = set_pause_state(
lambda d: (d.get("name") or "") == name
and (group_f is None or d.get("group", DEFAULT_GROUP) == group_f),
False,
)
print(f"Resumed {n} timer(s) named '{name}'.")
sys.exit(0)
if args.reset_all:
n = reset_timers(pred_all)
print(f"Reset {n} timer(s) (skipped entries without duration_seconds).")
sys.exit(0)
if args.reset_group:
g = args.reset_group
n = reset_timers(lambda d: d.get("group", DEFAULT_GROUP) == g)
print(f"Reset {n} timer(s) in group '{g}'.")
sys.exit(0)
if args.reset:
name = args.name or ""
if not name:
print("Error: --reset requires -n/--name (or use --reset-all / --reset-group)")
sys.exit(2)
n = reset_timers(
lambda d: (d.get("name") or "") == name
and (group_f is None or d.get("group", DEFAULT_GROUP) == group_f)
)
print(f"Reset {n} timer(s) named '{name}'.")
sys.exit(0)
if args.adjust is not None:
if not (args.name or "").strip():
print("Error: --adjust requires -n/--name (optional -g to narrow)")
sys.exit(2)
try:
delta = parse_adjust_delta(args.adjust)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
n = adjust_timers_by_name(args.name.strip(), delta, group_filter=group_f)
print(f"Adjusted {n} timer(s) by {args.adjust}.")
sys.exit(0)
if mgmt:
parser.error("Unexpected state.")
if not args.time_input:
parser.error("Please provide a time duration.")
full_time_str = " ".join(args.time_input)
try:
duration_seconds = parse_time(full_time_str)
except Exception as e:
print(f"Error: {e}")
print("Try 'timer --help' for more information.")
sys.exit(1)
if duration_seconds <= 0:
print("Error: Timer must be greater than 0.")
print("Try 'timer --help' for more information.")
sys.exit(1)
pid = os.getpid()
group = args.group if args.group is not None else DEFAULT_GROUP
args.group = group
start_time = time.time()
initial_end = start_time + duration_seconds
run_countdown_loop(args, pid, duration_seconds, initial_end)
if __name__ == "__main__":
main()