summaryrefslogtreecommitdiff
path: root/source/util/Jobs.mc
blob: d7342e3db12d470c8c22752102fa2bce6b358827 (plain) (blame)
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
// Author:  cirakg & claude ai
// Summary: Resumable jobs: long work split into small steps so no single event trips the watchdog.
//
// Connect IQ kills code that runs too long without returning to the system
// ("Watchdog Tripped"). The device files allow 120,000 bytecodes per event on
// the Forerunner 255/255S and 240,000 on the other targets; the simulator does
// not enforce this in test runs, so the only protection is design: anything
// that can take long (key derivation, SHA-512 batches, 2D barcode encoding,
// large imports) is a Job whose step() does a bounded amount of work.
//
// JobRunner drives a job from a timer, one step per tick, and calls back when
// it is done. Tests call Jobs.runToCompletion() instead, synchronously.

import Toybox.Lang;
import Toybox.Timer;

module Jobs {

    // Base class for resumable work.
    class Job {

        function initialize() {
        }

        // Do at most `budget` units of work. Returns true when the job is done.
        function step(budget as Number) as Boolean {
            return true;
        }
    }

    // Run a job to the end without yielding. Only for tests and work that is
    // known to be small.
    function runToCompletion(job as Job, budget as Number) as Void {
        while (!job.step(budget)) {
        }
    }

    // Drives a job from a timer: one step of `budget` units every TICK_MS.
    class JobRunner {

        // Pause between steps, so the UI stays responsive.
        static const TICK_MS = 50;

        private var _job as Job;
        private var _budget as Number;
        private var _onDone as Method() as Void;
        private var _timer as Timer.Timer?;

        function initialize(job as Job, budget as Number, onDone as Method() as Void) {
            _job = job;
            _budget = budget;
            _onDone = onDone;
        }

        // Start stepping; the first step runs on the first tick.
        function start() as Void {
            var timer = new Timer.Timer();
            timer.start(method(:onTick), TICK_MS, true);
            _timer = timer;
        }

        // Stop without finishing (for example, when the user leaves the screen).
        function cancel() as Void {
            var timer = _timer;
            if (timer != null) {
                timer.stop();
                _timer = null;
            }
        }

        function onTick() as Void {
            if (_job.step(_budget)) {
                cancel();
                _onDone.invoke();
            }
        }
    }
}