Skip to content

Commit 3f637d7

Browse files
committed
Timer always created so that stop won't result in an NRE and allows the instance to be restarted if needed.
1 parent a582dec commit 3f637d7

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/CronTimer.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public class CronTimer
1212
readonly CrontabSchedule schedule;
1313
readonly TimeZoneInfo tzi;
1414
readonly string id;
15-
Timer t;
15+
readonly Timer t;
1616

1717
public string tz { get; }
1818
public string Expression { get; }
@@ -26,6 +26,7 @@ public CronTimer(string expression, string tz = UTC, bool includingSeconds = fal
2626
tzi = TimeZoneInfo.FindSystemTimeZoneById(id);
2727
schedule = CrontabSchedule.Parse(expression, new CrontabSchedule.ParseOptions { IncludingSeconds = includingSeconds });
2828
OnOccurence += OnOccurenceScheduleNext;
29+
t = new Timer(s => OnOccurence(this, ea), null, InfiniteTimeSpan, InfiniteTimeSpan);
2930
}
3031

3132
void OnOccurenceScheduleNext(object sender, EventArgs e)
@@ -39,7 +40,7 @@ public void Start()
3940
{
4041
var delay = CalculateDelay();
4142
//Console.WriteLine($"Next for [{tz} {expression}] in {delay}.");
42-
t = new Timer(s => OnOccurence(this, ea), null, delay, InfiniteTimeSpan);
43+
t.Change(delay, InfiniteTimeSpan);
4344
}
4445

4546
TimeSpan CalculateDelay()
@@ -66,6 +67,6 @@ TimeSpan CalculateDelay()
6667

6768
public void Stop()
6869
{
69-
t.Dispose();
70+
t.Change(InfiniteTimeSpan, InfiniteTimeSpan);
7071
}
7172
}

0 commit comments

Comments
 (0)