How to use the .NET Timer class to trigger an event at a specific time?

前端 未结 9 1679

I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and

相关标签:
9条回答
  • 2020-12-01 00:43

    Echo to Dan's solution, using Timercallback is a quick and neat solution. Inside the method you want to schedule a task or subroutine to be run, use the following:

        t = New Timer(Sub()
                            'method call or code here'
                      End Sub, Nothing, 400, Timeout.Infinite)
    

    use of 'Timeout.Infinite' will ensure the callback will be executed only once after 400ms. I am using VB.Net.

    0 讨论(0)
  • 2020-12-01 00:47

    Taking VoteCoffees lead, here is a compact event based solution:

    public class DailyTrigger 
    {
        readonly TimeSpan triggerHour;  
    
        public DailyTrigger(int hour, int minute = 0, int second = 0)
        {
            triggerHour = new TimeSpan(hour, minute, second);
            InitiateAsync();        
        }
    
        async void InitiateAsync()
        {
            while (true)
            {
                var triggerTime = DateTime.Today + triggerHour - DateTime.Now;
                if (triggerTime < TimeSpan.Zero)
                    triggerTime = triggerTime.Add(new TimeSpan(24,0,0));
                await Task.Delay(triggerTime);
                OnTimeTriggered?.Invoke();
            }
        }
    
        public event Action OnTimeTriggered;
    }
    

    Consumer:`

    void Main()
    {
        var trigger = new DailyTrigger(16); // every day at 4:00pm
    
        trigger.OnTimeTriggered += () => 
        {
            // Whatever
        };  
    
        Console.ReadKey();
    }
    
    0 讨论(0)
  • 2020-12-01 00:48

    Task scheduler is a better option, and it can be easily used in C#, http://taskscheduler.codeplex.com/

    0 讨论(0)
提交回复
热议问题