跳到主要内容

github/tai

公开

Tai · Windows 软件与网站使用时长统计。上游 Planshit/Tai 的源码镜像,非灵栈原创;MIT 许可。来源:https://github.com/Planshit/Tai 。本次为手动同步,暂不提供安装包。

浏览文件

DateTimeObserver.cs

63 行 · 1.6 KB历史下载
1using Core.Event;
2using Core.Librarys;
3using Core.Servicers.Interfaces;
4using System;
5using System.Collections.Generic;
6using System.Diagnostics;
7using System.Linq;
8using System.Text;
9using System.Threading;
10using System.Threading.Tasks;
11using System.Timers;
12using Timer = System.Timers.Timer;
13
14namespace Core.Servicers.Instances
15{
16 public class DateTimeObserver : IDateTimeObserver
17 {
18 public event DateTimeObserverEventHandler OnDateTimeChanging;
19 private Timer timer;
20
21 public void Start()
22 {
23 Stop();
24 SetTimer();
25 }
26
27 private void SetTimer()
28 {
29 timer = new Timer();
30 timer.Elapsed += Timer_Tick;
31 DateTime now = DateTime.Now;
32 DateTime updateTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, 59, 59);
33 double diffMilliseconds = updateTime.Subtract(now).TotalMilliseconds;
34 if (diffMilliseconds < 0)
35 {
36 diffMilliseconds = 1;
37 }
38 timer.Interval = diffMilliseconds;
39 timer.Start();
40 Logger.Info("datetime observer start,interval(s):" + updateTime.Subtract(now).TotalSeconds);
41 }
42
43 private void Timer_Tick(object sender, EventArgs e)
44 {
45 timer.Stop();
46
47 DateTime nowTime = DateTime.Now;
48 OnDateTimeChanging?.Invoke(this, nowTime);
49
50 Thread.Sleep(2000);
51 SetTimer();
52 }
53
54 public void Stop()
55 {
56 if (timer != null && timer.Enabled)
57 {
58 timer.Stop();
59 timer.Dispose();
60 }
61 }
62 }
63}