| 1 | using Core.Event; |
| 2 | using Core.Librarys; |
| 3 | using Core.Servicers.Interfaces; |
| 4 | using System; |
| 5 | using System.Collections.Generic; |
| 6 | using System.Diagnostics; |
| 7 | using System.Linq; |
| 8 | using System.Text; |
| 9 | using System.Threading; |
| 10 | using System.Threading.Tasks; |
| 11 | using System.Timers; |
| 12 | using Timer = System.Timers.Timer; |
| 13 | |
| 14 | namespace 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 | } |