简体   繁体   中英

How to repeat method every 24 hours, by user input, when method is bool

I want to repeat this notifications every 24 hours. Temporary i`ve used Thread.Sleep(); but i know this is not good solution.

I think about using Time.Interval BUT I don`t know where to place that methods.
when i set things like aTimer.Elapsed and so on, according the documentation, My program just ignore the fact he need _timePicker input too.

My actual code looks like this


 [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        readonly INotificationManager notificationManager;
        DateTime _triggerTime;
        public MainPage()
        {
            InitializeComponent();
            Device.StartTimer(TimeSpan.FromSeconds(1), OnTimerTick);

            notificationManager = DependencyService.Get<INotificationManager>();
            notificationManager.NotificationReceived += (sender, eventArgs) =>
            {
                var evtData = (NotificationEventArgs)eventArgs;
                ShowNotification(evtData.Title, evtData.Message);
            };
        }
        bool OnTimerTick()
        {
            if (_switch.IsToggled && DateTime.Now >= _triggerTime)
            {
                DisplayAlert("Alert", "Time to take your pill! :) ", "OK");
                string title = $"Pill Reminder";
                string message = $"Take Your Pill :) ";
                notificationManager.ScheduleNotification(title, message);

                var duration = TimeSpan.FromSeconds(1);
                Vibration.Vibrate(duration);

                //24h interval, need some better solution
                Thread.Sleep(86400000);

            }
            return true;
        }

        void OnTimePickerPropertyChanged(object sender, PropertyChangedEventArgs args)
        {
            if (args.PropertyName == "Time")
            {
                SetTriggerTime();
            }
        }

        void OnSwitchToggled(object sender, ToggledEventArgs args)
        {
            SetTriggerTime();
        }

        void SetTriggerTime()
        {
            if (_switch.IsToggled)
            {
                _triggerTime = DateTime.Today + _timePicker.Time;
                if (_triggerTime < DateTime.Now)
                {
                    _triggerTime += TimeSpan.FromDays(1);
                }
            }
        }
        void ShowNotification(string title, string message)
        {
            Device.BeginInvokeOnMainThread(() =>
            {
                var msg = new Label()
                {
                    Text = $"Notification Received:\nTitle: {title}\nMessage: {message}"
                };

            });
        }
    }

To achieve this there are many different ways;

  • repeatedly check for system TimeAndDate and run code once it gets to X.
  • Shedule a task using a Timer. You can set interval to s/m/h and run code on TimerElapse.
  • using a Thread Sleep, very very bad way in this case, for many different reasons.

Here's an example sheduling a task:

using System;
using System.Timers;
 
namespace ScheduleTimer
{
    class Program
    {
        static Timer timer;
        static void Main(string[] args)
        {
            schedule_Timer();
            Console.ReadLine();
        }
        static void schedule_Timer()
        {
            Console.WriteLine("Timer Start");
            DateTime nowTime = DateTime.Now;
            //scheduled time HH,MM,SS [24 hours]
            DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 24, 0, 0, 0); 
            if (nowTime > scheduledTime)
            {
                scheduledTime = scheduledTime.AddDays(1);
            }
            double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
            timer = new Timer(tickTime);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }
        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Timer Stop");
            timer.Stop();
            Console.WriteLine("Hello, World!\n");
            schedule_Timer();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM